我将List绑定到ItemsControl。我表现得很好。但是当我向列表中添加一个字符串时,控件不会更新。我试图提升PropertyChanged事件以强制更新,但这没有帮助。我做错了什么?
这是XAML:
<Window x:Class="tt.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<StackPanel>
<ItemsControl ItemsSource="{Binding Strings}"/>
<Button Click="Button_Click">Add</Button>
</StackPanel>
</Window>
这是背后的代码:
public partial class MainWindow : Window, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public MainWindow()
{
InitializeComponent();
DataContext = this;
Strings.Add("One");
Strings.Add("Two");
}
public List<string> _strings = new List<string>();
public List<string> Strings
{
get { return _strings; }
set
{
if (_strings == value) return;
_strings = value;
if (this.PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs("Strings"));
}
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Strings.Add("More");
if (this.PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs("Strings"));
}
}
答案 0 :(得分:2)
将List<string>
更改为ObservableCollection<string>
(msdn)。
public ObservableCollection<string> _strings = new ObservableCollection<string>();
public ObservableCollection<string> Strings
{
get { return _strings; }
set
{
if (_strings == value) return;
_strings = value;
if (this.PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs("Strings"));
}
}