我在测试WPF数据绑定和命令绑定的时候,命令绑定在后台运行的时候可以运行,数据绑定却不更新,这是因为什么
主要功能就是点击按钮,count加1
点击按钮的时候命令绑定是正常的,监控count的确加1了,界面上textbox绑定的count,但是textbox没反应
以下是代码
这个是绑定的基类
public abstract class BindableBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(propertyName)));
public virtual bool Set<T>(ref T item, T value, [CallerMemberName] string propertyName = null)
{
if (EqualityComparer.Default.Equals(item, value)) return false;
item = value;
OnPropertyChanged(propertyName);
return true;
}
这个是mainwindow的viewmodel
class MainWindowViewModels:BindableBase
{
private int _count;
public int Count { get => _count; set => Set<int>(ref _count, value); }
private DelegateCommand buttonCommand;
public DelegateCommand ButtonCommand =>
buttonCommand ?? (buttonCommand = new DelegateCommand(CountADD));
private void CountADD()
{
this._count++;
}
这个是xaml代码和对应的C#代码
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition/>
Grid.RowDefinitions>
<TextBox Text="{Binding Count}" Grid.Row="0"/>
<Button Content="Click" Command="{Binding ButtonCommand}" Grid.Row="1"/>
Grid>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new MainWindowViewModels();
}
}
问题出在哪里了呢
您的代码中存在一个小错误,即您的 Set 方法的 PropertyChanged 事件中使用的是 nameof(propertyName) ,而不是 propertyName ,这会导致 PropertyChanged 事件总是传递的是字符串 "propertyName",而不是属性名称,从而导致数据绑定无法正常更新。
解决方法是将 PropertyChanged 事件中的 nameof(propertyName) 改为 propertyName ,如下所示:
public virtual bool Set<T>(ref T item, T value, [CallerMemberName] string propertyName = null)
{
if (EqualityComparer<T>.Default.Equals(item, value)) return false;
item = value;
OnPropertyChanged(propertyName); // 这里修改为直接使用 propertyName
return true;
}
修改后运行,会看到数据绑定正常更新。