2016-11-25 33 views
0

我有幾個ListViews取決於Dictionary<string,string>的內容。我還爲每個字典提供了一個更新其相關聯的ListView的函數。但是,這些必須手動調用,如果忘記了這可能會導致各種問題。只要字典中的任何值發生更改,是否可以調用函數?當字典內容變化時運行函數

我最初的想法是使用DataBinding,但Listview不支持這在WinForms或提出一些自定義事件,但我甚至不知道從哪裏開始。

有沒有簡單的方法來實現這一目標?

只是爲了澄清我說的東西,有這樣的效果:

Dictionary[key] = "this"; //Automatically runs UpdateDictionaryBox(); 
Dictionary.Add(key,value); //The same 
Dictionary.Remove(key); //And again 
+2

就像['ObservableDictionary'](http://blogs.microsoft.co.il/shimmy/2010/12/26/observabledictionarylttkey-tvaluegt-c/)? –

+0

爲什麼不使用'DataGridView'綁定到'BindingList ',其中T實現了'INotifyPropertyChanged'? –

+1

通常情況下,你可以通過封裝和單個責任類來避免這種情況。如果你有一個擁有這本字典的類,並且這個字典是私有的,那麼除了這個類以外,沒有人可以訪問它。然後,您可以提供更改,添加或刪除項目的屬性/方法。這是你唯一需要處理的地方,f.e.通過觸發一個可以處理的自定義事件,在那裏你可以調用'UpdateDictionaryBox' –

回答

0

所有信用添Schmelter爲他的評論使我這個解決方案!

本質,最簡單的方法是創建Dictionary<string,string>周圍的包裝類和ListView然後用它來實現所有需要的字典方法,並調用更新在.Add末,.Remove[key] = value

這樣,一旦類正確實現,它就會模擬數據綁定。

我的結果類是:

class DictionaryListViewPseudoBinder : IEnumerable 
{ 
    private ListView ListView { get; } 
    private Dictionary<string,string> Dictionary { get; set; } 

    public DictionaryListViewPseudoBinder(ListView listView) 
    { 
     ListView = listView; 
     Dictionary = new Dictionary<string, string>(); 
    } 

    public string this[string key] 
    { 
     get 
     { 
      return Dictionary.ContainsKey(key) ? Dictionary[key] : ""; 
     } 
     set 
     { 
      if (Dictionary.ContainsKey(key)) 
      { 
       Dictionary[key] = value; 
       RepopulateListView(); 
      } 
      else 
      { 
       MessageBox.Show("Dictionary does not contain key " + key + " aborting..."); 
      } 
     } 
    } 
    public void Add(string key, string value) 
    { 
     if (!Dictionary.ContainsKey(key)) 
     { 
      Dictionary.Add(key, value); 
      RepopulateListView(); 
     } 
     else 
     { 
      MessageBox.Show(string.Format("The Entry \"{0}\" already exists in {1}",key,ListView.Name)); 
     } 
    } 

    public void Remove(string key) 
    { 
     if (Dictionary.ContainsKey(key)) 
     { 
      Dictionary.Remove(key); 
     } 
    } 

    public bool ContainsKey(string key) 
    { 
     return Dictionary.ContainsKey(key); 
    } 

    public bool ContainsKVP(KeyValuePair<string, string> kvp) 
    { 
     if (!Dictionary.ContainsKey(kvp.Key)) 
     { 
      return false; 
     } 
     else 
     { 
      return Dictionary[kvp.Key] == kvp.Value; 
     } 
    } 
    private void RepopulateListView() 
    { 
     ListView.Items.Clear(); 
     foreach (KeyValuePair<string, string> kvp in Dictionary) 
     { 
      ListView.Items.Add(kvp.Key).SubItems.Add(kvp.Value); 
     } 
    } 

    public IEnumerator GetEnumerator() 
    { 
     return Dictionary.GetEnumerator(); 
    } 
} 

注:以上還沒有完全測試,並不是所有的方法都在這個時候完全實現,但它表明需要此功能的總體框架。

+0

不要在包含字典的情況下使用contains檢查,它將導致查找一個用於包含,另一個用於if內的操作。使用try方法(TryAdd等)來代替。 –