【问题标题】:WPF Databinding, value won't updateWPF数据绑定,值不会更新
【发布时间】:2016-10-30 22:30:23
【问题描述】:

我知道这是一个非常常见的问题,但是在更改 buttonContent 的“默认”时,我无法让按钮更新为“Pressed1”和“Pressed2”内容。看了几个问题,我找不到适合我的答案,我根本找不到这里有什么问题,所以这里是糟糕的代码:

带有按钮的窗口

public partial class MainWindow : Window
{
    Code_Behind cB;
    public MainWindow()
    {
        cB = new Code_Behind();
        this.DataContext = cB;
        InitializeComponent();
    }
    private void button_Click(object sender, RoutedEventArgs e)
    {
        cB.buttonPressed();
    }
}

这是单独的类

   public class Code_Behind : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    private string _buttonContent = "Default";
    public string buttonContent
    {
        get { return _buttonContent; }
        set { 
                if (_buttonContent != value) 
                    {
                        buttonContent = value;
                        OnPropertyChanged("buttonContent"); 
                    } 
            }
    }
    public void buttonPressed()
    {
        int timesPressed = 0;
        if (timesPressed != 1)
        {
                _buttonContent = "Pressed1";
                timesPressed++;
        }
        else if (timesPressed != 2)
        {
                _buttonContent = "Pressed2";
                timesPressed++;
                timesPressed = 0;
        }
    }
    protected void OnPropertyChanged(string name)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
    }
}

【问题讨论】:

    标签: c# wpf data-binding wpf-controls


    【解决方案1】:

    您设置的不是属性,而是支持字段。因此不会触发PropertyChanged 事件。

    替换

    _buttonContent = "Pressed1";
    ...
    _buttonContent = "Pressed2";
    

    buttonContent = "Pressed1";
    ...
    buttonContent = "Pressed2";
    

    除此之外,使用 Pascal 大小写编写属性名称是一种被广泛接受的约定,即 ButtonContent 而不是 buttonContent

    此外,您的属性设置器看起来很奇怪(可能是因为您试图在一行中压缩太多代码)。

    代替

    set
    {
        if (_buttonContent != value)
        {
            _buttonContent = value;
        } 
        OnPropertyChanged("buttonContent");
    }
    

    应该是的

    set
    {
        if (_buttonContent != value)
        {
            _buttonContent = value;
            OnPropertyChanged("buttonContent");
        } 
    }
    

    【讨论】:

    • 是的,这实际上就是问题所在。好吧,它从来没有解释过属性是如何工作的。绑定到类的对象实例或直接绑定到类之间有区别吗?
    • 绑定“直接到类”意味着绑定到类(即静态)属性?从这里开始阅读:Data Binding Overview.
    • 顺便说一下,在 MVVM 架构模式中,您所说的“分离类”(命名为 Code_Behind)通常称为 视图模型
    • 是的,我读过一次,但它并不能真正回答可能出现的问题。它讲述了它是如何工作的以及它做了什么,而不是“为什么”。编辑:我将补充一点,大部分代码只是练习掌握数据绑定等。我确实学习了 C# 编程的基础知识,但仍有一些事情我需要自己去探索
    • 不确定您在此处指的是哪个“它”。无论如何,通过触发 PropertyChanged 事件来通知 WPF 数据绑定其源属性的值更改。如果未触发事件,则不会通知绑定,因此 UI 不会更新。
    猜你喜欢
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多