c# - 将 ObservableCollection 绑定(bind)到 ListBox ItemsSource

标签 c# wpf data-binding listbox observablecollection

我在从 ObservableCollection 的更改更新列表框时遇到一些问题。我将 ListBox 的 ItemsSource 绑定(bind)到 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");
        }
    }
}

最佳答案

输入MyStrings = new ObservableCollection<string> { "Boop" }; InitializeComponent(); 之前的行

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

当前代码绑定(bind)在 ItemsSource="{Binding MyStrings}"MyStrings在初始化之前需要通知更新MyStrings创建集合时。

未经通知ItemsSource停留null .

关于c# - 将 ObservableCollection 绑定(bind)到 ListBox ItemsSource,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50741957/

相关文章:

c# - 使用 EMGU CV C# 中的 HOGDescriptor 获取图像的 HOG 描述符

c# - 在 WPF MVVM 的 GridView 中动态创建列

javascript - 如何从 ngModel 渲染 HTML 标签?

visual-studio-2008 - 在 DataSource 上找不到 DataMember 属性 [ObjectName]

c# - 如果 .Count == 0 条件运算符不显示

c# - .Net Metro App 中的 MarkUpExtension

wpf - 将 Enum 转换为 TextBlock 文本中的字符串

wpf - SilverLight 类似于 WPF 中的 Datagrid 分页吗?

c# - DataBinding 到 UserControl 内部的 UserControl

c# - 附加到序列化集合