我在让我的 ListBox 从 ObservableCollection 的更改中更新时遇到了一些麻烦。我将 ListBox 的 ItemsSource 绑定到 ObservableCollection,但 ListBox 仍然拒绝显示任何内容。
如果我实现 INotifyPropertyChanged,并在每次更改集合时引发属性更改事件,则它可以工作。但是我认为如果我使用 ObservableCollection 就不必这样做了。
我应该怎么做才能使 ListBox 更新并适当地显示 ObservableCollection?
Xml:
<Window x:Name="window" x:Class="testApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:testApp"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525" DataContext="{Binding Mode=OneWay, RelativeSource={RelativeSource Self}}">
<StackPanel Margin="0">
<Button Content="Add" HorizontalAlignment="Left" Height="24" Margin="5,5,0,0" Width="100" Click="Button_Click"/>
<ListBox Height="140" Margin="5,5,5,0" VerticalAlignment="Top" ItemsSource="{Binding MyStrings, ElementName=window}"/>
</StackPanel>
</Window>
代码隐藏:
namespace testApp
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
MyStrings = new ObservableCollection<string> { "Boop" };
}
public ObservableCollection<string> MyStrings { get; private set; }
private void Button_Click(object sender, RoutedEventArgs e)
{
MyStrings.Add("New String");
}
}
}
相关分类