gpt4 book ai didi

c# - WPF 中的 INotifyPropertyChanged

转载 作者:太空狗 更新时间:2023-10-30 00:16:14 25 4
gpt4 key购买 nike

尝试了解 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 始终为空。

最佳答案

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

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

this.DataContext = this;

然后更改 Binding 以便引用该属性:

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

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

this.RaisePropertyChanged("MyList");

关于c# - WPF 中的 INotifyPropertyChanged,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8062436/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com