c# - 绑定不更新 WPF
问题描述
我正在尝试将 int 绑定到简单应用程序中的标签。这个想法是,当按下按钮时,int 和标签都会更新。
我已经尽可能地简化了代码,但我看不到问题所在。
我认为问题在于NotifyPropertyChanged(String propertyName)
在运行时开始标签的内容会使用 int 的值进行更新。但是,当 int 更新时,标签不会。
主窗口.xaml
<Window x:Class="Press.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<StackPanel>
<StackPanel Orientation="Horizontal">
<Label Content="Presses: "/>
<Label Content="{Binding Path=PressCount}"/>
</StackPanel>
<Button Content="Press Me" Click="PressMe_Click"/>
</StackPanel>
</Window>
主窗口.xaml.cs
using System;
using System.Windows;
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace Press
{
public partial class MainWindow : Window
{
public int pressCount = 0;
public int PressCount {
get {
return pressCount;
}
private set {
if(value != pressCount)
{
pressCount = value;
NotifyPropertyChanged();
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public MainWindow()
{
InitializeComponent();
DataContext = this;
}
private void PressMe_Click(object sender, RoutedEventArgs e)
{
PressCount++;
Console.WriteLine(PressCount);
}
}
}
解决方案
你需要MainWindow
实现接口INotifyPropertyChanged
推荐阅读
- unity3d - 检测到使用 UNITY_MATRIX_MV
- reactjs - 如何使用 getDerivedStateFromProps
- amazon-web-services - 如何连接到通过 EC2 上的 PORT 8090 连接的 haas 在线交易服务器
- selenium-webdriver - Cypress.io 真的比 Selenium 快吗?
- rcpp - List中唯一的rcpp糖
- python - 是否有将极坐标网格映射到笛卡尔网格的快速 Numpy 算法?
- java - 初始化错误预期文件黄瓜运行 .jar
- javascript - 从 JSON 对象中删除所有键
- android - 自定义键盘崩溃
- r - R中的正则表达式以提取满足负面位置条件的话语