将ObservableCollection绑定到ListBox ItemsSource

时间:2018-06-07 13:02:32

标签: c# wpf data-binding listbox observablecollection

我在使用ListBox更改我的ObservableCollection更新时遇到了一些麻烦。我将ListBox的ItemsSource绑定到ObservableCollection,但ListBox仍然拒绝显示任何内容。

如果我实现了INotifyPropertyChanged,并且每当我更改集合时引发属性更改事件,它都可以。但我认为如果我使用的是ObservableCollection,我就不必这样做了。

如何更新ListBox并正确显示ObservableCollection?

的Xaml:

<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");
        }
    }
}

1 个答案:

答案 0 :(得分:2)

MyStrings = new ObservableCollection<string> { "Boop" };

之前添加InitializeComponent();
public MainWindow()
{
    MyStrings = new ObservableCollection<string> { "Boop" };
    InitializeComponent();
}

ItemsSource="{Binding MyStrings}"中的当前代码绑定在初始化之前读取MyStrings,并且在创建集合时需要通知更新MyStrings

没有通知ItemsSource停留null