すべてのクレジット!
本質的には、最も簡単な方法は、Dictionary<string,string>
のラッパークラスを作成することであり、ListView
はその後など
を必要としている辞書すべてのメソッドを実装するためにこれを使用して
.Remove
[key] = value
、
.Add
の最後に更新を呼び出します
このように、クラスが正しく実装されると、データバインディングをエミュレートします。上記は、まだ完全にテストされておらず、すべてのメソッドが完全にこの時点で実現されているわけではないが、それはこの機能のために必要な一般的な枠組みを示す:
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();
}
}
NB:
マイ得られたクラスです。
['ObservableDictionary']のようなもの(http://blogs.microsoft.co.il/shimmy/2010/12/26/observabledictionarylttkey-tvaluegt-c/)? –
Tが 'INotifyPropertyChanged'を実装した' BindingList 'にバインドされた' DataGridView'を使わないのはなぜですか? –
通常、カプセル化と単一の責任クラスによってこのようなことを避けることができます。この辞書を保持するクラスがあり、これがプライベートであれば誰もアクセスできませんでした。次に、アイテムを変更、追加、または削除するプロパティ/メソッドを提供することができます。これはあなたがこれを処理する必要がある唯一の場所です。 'UpdateDictionaryBox'を呼び出すことができます。 –