簡體   English   中英

添加新項目后更新列表框

[英]Updating the listbox after adding a new item

我正在使用WPF和C#我有一個按鈕打開一個窗口,其中還包含一個按鈕,用於將一個User對象項添加到列表框中,我希望在插入后更新列表框索引。 我明白解決方案是關於使用可觀察的INotifyCollectionChanged類,但實際上我不知道如何以及在何處使用它們。 你能幫我確定實施,注冊,開火等的內容和地點。


編輯:我在Quartermeister的幫助下成功完成了我的用戶對象收集在列表中,但現在我想做同樣的事情,我的對象被收集在字典中

最簡單的方法是使用System.Collections.ObjectModel.ObservableCollection<T>作為列表。 這為您實現了INotifyCollectionChangedINotifyPropertyChanged

您將在此類型的DataContext對象上擁有一個屬性,並使用ListBox.ItemsSource上的數據綁定將其綁定到該屬性。 當集合發生更改時,ListBox將自動更新其元素列表。

在您的DataContext類中:

public class MyClass
{
    public ObservableCollection<string> Items { get; set; }
}

在Xaml中:

<ListBox ItemsSource="{Binding Items}">
</ListBox>

聽起來你也想要一個可觀察的字典,但不幸的是框架中沒有一個。 您可以嘗試使用Dr. Wpf的ObservableDictionary實現從他的帖子“我可以將我的ItemsControl綁定到字典嗎?”

實現可觀察的字典很難。 維護一個包含字典值的並行可觀察集合要簡單得多。 將視圖綁定到該集合,並確保向字典添加或從字典中刪除值的任何代碼都會更新字典和並行集合。

如果你真的想發瘋,你可以實現ObservableCollection的子類來保存你的對象,並使該類維護字典,例如:

public class KeyedObject
{
    public string Key { get; set; }
    public object Value { get; set; }
}

public class ObservableMappedCollection : ObservableCollection<KeyedObject>
{
    private Dictionary<string, KeyedObject> _Map;

    public ObservableMappedCollection(Dictionary<string, KeyedObject> map)
    {
        _Map = map;    
    }

    protected override void InsertItem(int index, KeyedObject item)
    {
        base.InsertItem(index, item);
        _Map[item.Key] = item;
    }

    protected override void RemoveItem(int index)
    {
        KeyedObject item = base[index];
        base.RemoveItem(index);
        _Map.Remove(item.Key);
    }

    protected override void ClearItems()
    {
        base.ClearItems();
        _Map.Clear();
    }

    protected override void SetItem(int index, KeyedObject item)
    {
        KeyedObject oldItem = base[index];
        _Map.Remove(oldItem.Key);
        base.SetItem(index, item);
        _Map[item.Key] = item;
    }
}

上面有很多潛在的問題,主要是與重復的鍵值有關。 例如,如果你要添加一個鍵已經在地圖中的對象, SetItemSetItem 答案實際上取決於您的申請。 這樣的問題也暗示了為什么框架中沒有可觀察的字典類。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM