【问题标题】:Databinding ObservableCollection to a ListBox将 ObservableCollection 数据绑定到 ListBox
【发布时间】:2014-09-28 14:24:06
【问题描述】:

我一直在尝试找出将类的 ObservableCollection 绑定到具有 TextBox DataTemplate 的 ListBox 的正确方法。我试图在WPF binding: Set Listbox Item text color based on property 中实现代码,但这还没有让我走得很远。我是 WPF DataBinding 的新手,在简单的情况下最多以编程方式设置 ItemsSource。

我有这门课

public class item
{
    public string guid;
    public bool found;
    public bool newItem;
    public Brush color;
}

和下面的 ObservableCollection

public ObservableCollection<item> _items;

public Window()
{
    InitializeComponent();
    _items = new ObservableCollection<item>();
}

在代码的其他地方,我通过

将项目添加到集合中
_items.Add(new item() { guid = sdr.GetString(0), found = false, newItem = false, color = Brushes.Red });

这里是 ListBox 的简化 XAML

<ListBox x:Name="ListBox_Items">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text=GUID_HERE Foreground=COLOR_HERE/>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

我已经尝试了几种不同的方法来使其正常工作,但对于它们中的任何一个,ListBox 都没有更新。有人可以在这里帮助我指出正确的方向吗?

【问题讨论】:

    标签: c# wpf data-binding listbox observablecollection


    【解决方案1】:

    四件事:

    您的项目类需要使用公共属性:

    public class item
    {
        public string guid { get; set; }
        public bool found { get; set; }
        public bool newItem { get; set; }
        public Brush color { get; set; }
    }
    

    您需要将ItemsSource设置为集合,并设置当前的DataContext

    public Window()
    {
        InitializeComponent();
        DataContext = this;
    
        _items = new ObservableCollection<item>();
        ListBox_Items.ItemsSource = _items;     
    }
    

    您需要更新您的 DataTemplate 以使用您的 POCO 的属性名称

    <ListBox x:Name="ListBox_Items">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding guid}" Foreground="{Binding color}"/>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
    

    【讨论】:

    • 谢谢!我一直错过 DataContext = this;以及明确定义 get 和 set。
    【解决方案2】:

    我认为您忘记将 ListBox 绑定到集合本身。

    您的 XAML 应如下所示:

    <ListBox x:Name="ListBox_Items" ItemsSource="{Binding _items}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <TextBlock Text=GUID_HERE Foreground=COLOR_HERE/>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
    

    如果您想更改集合中项目的属性(并且更改显示在 UI 上),您应该在“item”类中实现 INotifyPropertyChanged(请参阅MSDN)接口。

    【讨论】:

    • 我已经完成了多种不同的形式。我把它省略了,因为我不确定那里到底发生了什么。我已经使用 {binding _items} 和 {binding guid}, {binding color} 简单地尝试过你所拥有的,但无济于事
    猜你喜欢
    • 1970-01-01
    • 2012-12-16
    • 2018-09-11
    • 2013-12-31
    • 1970-01-01
    • 1970-01-01
    • 2013-10-15
    • 2015-08-04
    • 1970-01-01
    相关资源
    最近更新 更多