【问题标题】:Data binding does not update ui element数据绑定不更新 ui 元素
【发布时间】:2011-12-25 08:52:45
【问题描述】:

我无法使用 WPF 完成绑定。

我有一个类似的模型类:

public class DataModel 
{
     private double _temp;

     public double Temperature 
     {
        set
        {
            _temp= value;
            OnPropertyChanged("Temperature");
        }

        get { return this._temp; }
     }
 }

这个模型派生自一个类 BaseDataModel

public abstract class BaseDataModel
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = this.PropertyChanged;
        if (handler != null)
        {
            var e = new PropertyChangedEventArgs(propertyName);
            handler(this, e);

        }
     }
 }

我现在在另一个名为 DataViewModel 的类中有一个 DataModel 对象列表,该列表名为“Values”。在该类之上的一个类中,我有一个需要在运行时动态创建的 UserControl,因此绑定在后面的代码中完成,如下所示:

列表上方的某处:

DataViewModel model = new DataViewModel();

以及绑定本身:

curbinding = new Binding();
curbinding.Source = model.Values;
curbinding.Path = new PropertyPath("Temperature");
curbinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
myTextBox.SetBinding(TextBox.TextProperty, curbinding); 

我知道 PropertyChanged 被触发,但文本框的值没有更新。我就是想不通为什么?当我第一次创建绑定时,文本框的文本会更新,但是当我更改温度的值时,什么也没有发生。 我没有想到什么吗?

我不得不说,这个应用程序有很多其他的类,而且更复杂,但正如我所说,值只更新一次,永远不会再更新。

【问题讨论】:

  • 究竟在哪里实现 INotifyPropertyChanged?
  • 我很愚蠢......我只是发现我偶然删除了那个部分,甚至再也没有想过它......解决方案是从 INotifyPropertyChanged 派生,如下所示:BaseDataModel:INotifyPropertyChanged 非常感谢很多! :)

标签: wpf data-binding


【解决方案1】:

如果您没有阅读 cmets,我只是忘记实现 INotifyPropertyChanged ...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多