【发布时间】:2016-09-07 12:53:34
【问题描述】:
我在 WPF 中将字典绑定到 ListView。
<ListView x:Name="listView" HorizontalAlignment="Left" Height="100" Margin="30,324,0,0" VerticalAlignment="Top" Width="270" ItemsSource="{Binding ArchiveDataDB}">
<ListView.View>
<GridView>
<GridViewColumn Header="Archive Name"
DisplayMemberBinding="{Binding Key}" />
<GridViewColumn Header="Data DB Amount"
DisplayMemberBinding="{Binding Value}" />
</GridView>
</ListView.View>
</ListView>
那是我的字典:
public Dictionary<string, int> ArchiveDataDB
{
get
{
if(_archiveDataDB == null)
{
_archiveDataDB = new Dictionary<string, int>();
_archiveDataDB.Add("Master Data", 0);
}
return _archiveDataDB;
}
set
{
_archiveDataDB = value;
}
}
我还有一个按钮,它应该从 2 个文本框中获取一个字符串和一个 int 并将这 2 个信息添加到列表中
public void AddEntry(object args)
{
ArchiveDataDB.Add(ArchiveName, DataDBAmount);
OnPropertyChanged("ArchiveDataDB");
}
OnPropertyChanged 方法是从 INotifyPropertyChanged 接口实现的。
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
出于测试目的,我在 AddEntry 方法中添加了一个MessageBox.Show 并显示了所有条目。我 100% 确定新键和值已添加到字典中,但 ListView 没有更新。
感谢您的帮助
最大
【问题讨论】:
-
你是不是忘记了构造函数中的
this.DataContext = this;。 -
Two Way Data Binding With a Dictionary in WPF 可能重复我会推荐@Ray 的解决方案
标签: c# wpf listview dictionary mvvm