我有一個Dictionary<string, string>
,並希望讓用戶查看和編輯內容,可能會添加新的條目。我應該怎麼做?顯示可編輯詞典的最簡單方法是什麼?
輸入驗證,處理源字典的動態更新,看起來不錯,是一種獎勵。
我有一個Dictionary<string, string>
,並希望讓用戶查看和編輯內容,可能會添加新的條目。我應該怎麼做?顯示可編輯詞典的最簡單方法是什麼?
輸入驗證,處理源字典的動態更新,看起來不錯,是一種獎勵。
絕對最簡單的解決方案是將數據錶轉換爲數據表並將其綁定到該數據表。
DataTables支持所需的所有數據綁定支持,並允許您添加和刪除行。
用戶完成後,可以將數據表的內容再次複製到您的字典中。
天真而骯髒,但它會完成工作。
Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("foo", "bar");
//translate and bind
DataTable dt = new DataTable();
dt.Columns.Add("Key", typeof(string));
dt.Columns.Add("Value", typeof(string));
dict
.ToList()
.ForEach(kvp => dt.Rows.Add(new object [] {kvp.Key,kvp.Value}));
//allows you to add uniqueness constraint to the key column :-)
dt.Constraints.Add("keyconstraint", dt.Columns[0], true);
myDataGridView.DataSource = dt;
並將其轉化回字典:
Dictionary<string, string> dict = new Dictionary<string, string>();
DataTable dt = (DataTable)myDataGridView.DataSource;
dt.AsEnumerable()
.ToList()
.ForEach(row => dict.Add(row[0] as string, row[1] as string));
顯示字典等數據結構的方法很多,全部取決於所使用的技術以及要提供給UI的佈局。
我認爲網格是最簡單的一個,但您也可以嘗試其他控件。
如果您想提升用戶體驗並創建一個良好的用戶界面,我建議您學習WPF:使用該技術,您可以對數據結構進行佈局,並輕鬆進行更改,直至獲得最佳結果。
我僅限於的WinForms,可悲。你能展示或鏈接到一個簡單的代碼示例嗎? – mafu 2010-05-09 19:55:13
這裏是一個例子,但是如果你google的話你可以找到很多的例子: http://www.dev102.com/2008/03/07/binding-a-wpf-control-to-a-dictionary/ – 2010-05-09 20:29:15