WPF中的INotifyPropertyChanged [英] INotifyPropertyChanged in WPF

查看:72
本文介绍了WPF中的INotifyPropertyChanged的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试了解WPF。这是我的测试类:

Try to understand WPF. This is my test classes:

    public partial class MainWindow : Window, INotifyPropertyChanged
{
    private ObservableCollection<string> _myList = new ObservableCollection<string>();

    public ObservableCollection<string> MyList
    {
        get { return _myList; }
        set
        {
            _myList = value;
            RaisePropertyChanged("_myList");
        }
    }

    public MainWindow()
    {
        InitializeComponent();
        comboBox1.DataContext = _myList;
    }

    private void button1_Click(object sender, RoutedEventArgs e)
    {
        MyList = AnotherClass.SomeMethod();
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void RaisePropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

internal static class AnotherClass
{
    public static ObservableCollection<string> SomeMethod()
    {
        return new ObservableCollection<string> {"this","is","test"};
    }
}

这是XAML

<Grid>
    <ComboBox Height="23" HorizontalAlignment="Left" Margin="65,51,0,0" Name="comboBox1" VerticalAlignment="Top" Width="120" ItemsSource="{Binding}" />
    <Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="310,51,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />
</Grid>

如何使此代码有效?我希望在单击按钮并更新MyList后更改ComboBox数据。 PropertyChangedEventHandler始终为null。

How to make this code work? I want ComboBox data will be changed after I click on the button and MyList is updated. PropertyChangedEventHandler is always null.

推荐答案

问题是您将原始列表直接设置到 Window.DataContext ,因此没有人会监听Windows的 PropertyChanged 事件。

The problem is that you are directly setting the original list onto the Window.DataContext, so nothing ever listens to the windows' PropertyChanged event.

要解决此问题,请设置 DataContext 到窗口本身:

To solve this, set the DataContext to the window itself:

this.DataContext = this;

然后更改 Binding 属性:

<ComboBox ItemsSource="{Binding MyList}" />

您还需要更改属性定义,以便使用属性的名称,而不是成员名称:

You will also need to change your property definition so that it raises the name of the property being changed, not the name of the member:

this.RaisePropertyChanged("MyList");

这篇关于WPF中的INotifyPropertyChanged的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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