傲林 2023-03-09 10:50 采纳率: 83.3%
浏览 30
已结题

WPF数据绑定不更新

我在测试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();
        }
    }

问题出在哪里了呢

  • 写回答

2条回答 默认 最新

  • 陈书予 2023年6月份城市(北京)之星TOP 1 2023-03-09 12:10
    关注

    您的代码中存在一个小错误,即您的 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;
    }
    

    修改后运行,会看到数据绑定正常更新。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 3月17日
  • 已采纳回答 3月9日
  • 创建了问题 3月9日

悬赏问题

  • ¥15 对于这个复杂问题的解释说明
  • ¥50 三种调度算法报错 采用的你的方案
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败