首页 > 解决方案 > Can't get Dictionary<> (Or ObservableCollection) to bind to ListView

问题描述

I am trying to get a Dictionary to bind to a ListView. Having not worked, I changed the Datatype to ObservableCollection> but still no joy. I know I'm missing something silly but....

The data is readonly, meaning that the UI will not update it, only the code behind.

The XAML:

<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:sys="clr-namespace:System;assembly=mscorlib"
    DataContext="{Binding RelativeSource={RelativeSource Self}}">  

        <ListView Grid.Column="1" Background="Orange" ItemsSource="{Binding MyItems}">
            <ListView.View>
                <GridView>
                    <GridViewColumn Header="Item" DisplayMemberBinding="{Binding Key}"/>
                    <GridViewColumn Header="Quantity" DisplayMemberBinding="{Binding Value}"/>
                </GridView>
            </ListView.View>
        </ListView>

The DataObject:

public ObservableCollection<KeyValuePair<string, int>> MyItems{ get; set; }

And the assignment:

this.MyItems = new ObservableCollection<KeyValuePair<string, int>>(
            PIData.GetNeededItems(itemName));

标签: wpfdata-binding

解决方案


您应该在调用 InitializeComponent 之前分配 MyItems 属性。

public MainWindow()
{
    MyItems = new ObservableCollection<KeyValuePair<string, int>>(
        PIData.GetNeededItems(itemName));

    InitializeComponent();
}

如果这不可能,请实施 INotifyPropertyChanged:

public partial class MainWindow : Window, INotifyPropertyChanged
{
    ...

    public event PropertyChangedEventHandler PropertyChanged;

    private ObservableCollection<KeyValuePair<string, int>> myItems;

    public ObservableCollection<KeyValuePair<string, int>> MyItems
    {
        get { return myItems; }
        set
        {
            myItems = value;
            PropertyChanged?.Invoke(this,
                new PropertyChangedEventArgs(nameof(MyItems)));
        }
    }
}

推荐阅读