【问题标题】:WPF ListView won't update binded dictionaryWPF ListView 不会更新绑定的字典
【发布时间】: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 没有更新。

感谢您的帮助

最大

【问题讨论】:

标签: c# wpf listview dictionary mvvm


【解决方案1】:

要快速解决这个问题,你可以使用这个:

替换

return _archiveDataDB;

return _archiveDataDB.ToDictionary(x=>x.Key, y=>y.Value);

还有这一行

ArchiveDataDB.Add(ArchiveName, DataDBAmount);

这一行

_archiveDataDB.Add(ArchiveName, DataDBAmount);

当 ListView 获得一个新的字典实例时,它会更新布局。

但要使其正确,您应该使用一些实现 od ObservableDictionary 或使用其他可观察集合。

例如从这里:

.NET ObservableDictionary

希望对你有帮助。

【讨论】:

    猜你喜欢
    • 2011-01-23
    • 1970-01-01
    • 2016-11-20
    • 2016-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多