WPF数据绑定问题在代码中定义不更新UI元素 [英] Problem with WPF Data Binding Defined in Code Not Updating UI Elements

查看:98
本文介绍了WPF数据绑定问题在代码中定义不更新UI元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要定义新的UI元素以及代码中的数据绑定,因为它们将在运行时实现。以下是我正在尝试做的简化版本。

I need to define new UI Elements as well as data binding in code because they will be implemented after run-time. Here is a simplified version of what I am trying to do.

数据模型:

public class AddressBook : INotifyPropertyChanged
{
    private int _houseNumber;
    public int HouseNumber
    {
        get { return _houseNumber; }
        set { _houseNumber = value; NotifyPropertyChanged("HouseNumber"); }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected void NotifyPropertyChanged(string sProp)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(sProp));
        }
    }
}

在代码中绑定: p>

Binding in Code:

AddressBook book = new AddressBook();
book.HouseNumber = 123;
TextBlock tb = new TextBlock();
Binding bind = new Binding("HouseNumber");
bind.Source = book;
bind.Mode = BindingMode.OneWay;
tb.SetBinding(TextBlock.TextProperty, bind); // Text block displays "123"
myGrid.Children.Add(tb);
book.HouseNumber = 456; // Text block displays "123" but PropertyChanged event fires

当数据首次绑定时,文本块更新为正确的房屋号码。然后,如果稍后更改代码中的房屋号码,则该图书的PropertyChanged事件将触发,但文本块不会更新。任何人都可以告诉我为什么?

When the data is first bound, the text block is updated with the correct house number. Then, if I change the house number in code later, the book's PropertyChanged event fires, but the text block is not updated. Can anyone tell me why?

谢谢,

推荐答案

它的根源是我传递给PropertyChangedEventArgs的字符串没有与属性的名称完全匹配。我有这样的东西:

The root of it was that the string I passed to PropertyChangedEventArgs did not EXACTLY match the name of the property. I had something like this:

public int HouseNumber
{
    get { return _houseNumber; }
    set { _houseNumber = value; NotifyPropertyChanged("HouseNum"); }
}

应该是这样的:

public int HouseNumber
{
    get { return _houseNumber; }
    set { _houseNumber = value; NotifyPropertyChanged("HouseNumber"); }
}

Yikes!感谢您向正确的方向推进。

Yikes! Thanks for the push in the right direction.

这篇关于WPF数据绑定问题在代码中定义不更新UI元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆