【问题标题】:INotifyPropertyChanged in WPFWPF 中的 INotifyPropertyChanged
【发布时间】:2011-12-25 03:13:51
【问题描述】:

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

    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 始终为空。

【问题讨论】:

    标签: c# wpf data-binding inotifypropertychanged


    【解决方案1】:

    我认为你有两个问题:

    1) 绑定应该是:{Binding MyList}

    2) 在 MyList 设置器上,您应该使用 RaisePropertyChanged("MyList");

    【讨论】:

      【解决方案2】:

      问题是您将原始列表直接设置到Window.DataContext,所以没有任何东西会监听windows的PropertyChanged事件。

      要解决这个问题,请将DataContext 设置为窗口本身:

      this.DataContext = this;
      

      然后更改Binding所以参考属性:

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

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

      this.RaisePropertyChanged("MyList");
      

      【讨论】:

        猜你喜欢
        • 2021-09-07
        • 2015-06-22
        • 2011-12-17
        • 2010-10-04
        • 1970-01-01
        • 2011-08-12
        • 1970-01-01
        相关资源
        最近更新 更多