我在测试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<T>.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();
}
}
问题出在哪里了呢