wpf - 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));
解决方案
您应该在调用 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)));
}
}
}
推荐阅读
- laravel - 结果基于 laravel 中 groupBy 的最大日期
- python - 在存储帐户python(天蓝色函数)之间移动或复制文件(blob)?
- android - android.widget.LinearLayout 没有设置 NavController
- java - Java代码抛出执行“错误:无法打开Parameters.properties,请确保它在您当前的工作目录中”
- java - FluentProducerTemplate - 请求到错误的休息端点
- ios - UITabBarController 共享数据模型 - 从任何地方共享和更新模型
- elasticsearch - 如何在自己的自定义 kibana 插件中使用 dashbaord 插件?
- python - 如何在使用搁置时强制 python 创建一个 db 而不是 dat 文件?
- javascript - React 功能组件测试文件无法更新状态值并调用其 props 函数
- matlab - 在 MNE-python 中,为什么来自时频表示(tfr)的功率数据尺度与功率谱密度(PSD)不同?