![](/img/trans.png)
[英]ComboBox binding with DisplayMemberPath and SelectedValuePath does not work as expected
[英]How to set DisplayMemberPath and SelectedValuePath for a binding from DataRow from System.Data?
如何設置System.Data中DataRow的綁定的DisplayMemberPath和SelectedValuePath?
這就是我在做的,對嗎?
DataSet ds = new DataSet();
DataTable dt = new DataTable("tb1");
dt.Columns.Add("ID");
dt.Columns.Add("Name");
ds.Tables.Add(dt);
DataRow dr1 = ds.Tables[0].NewRow();
dr1["ID"] = 1;
dr1["Name"] = "Edwin";
DataRow dr2 = ds.Tables[0].NewRow();
dr2["ID"] = 2;
dr2["Name"] = "John";
DataRow dr3 = ds.Tables[0].NewRow();
dr3["ID"] = 3;
dr3["Name"] = "Dave";
ds.Tables[0].Rows.Add(dr1);
ds.Tables[0].Rows.Add(dr2);
ds.Tables[0].Rows.Add(dr3);
comboBox1.DisplayMemberPath = "Name";
comboBox1.SelectedValuePath = "ID";
foreach (DataRow item in ds.Tables[0].Rows)
{
comboBox1.Items.Add(item);
}
您正在將DataRow
對象添加到ComboBox
,並且DataRow
沒有標題為ID
和Name
屬性(從技術上講,它們確實具有Name
屬性,但這不是您要考慮的屬性)
一個簡單的記住方法是使用DisplayMemberPath
和SelectedValuePath
,您需要能夠使用DataItem.PropertyName
的語法訪問該屬性,因此在您的情況下,它試圖訪問DataRow.ID
和DataRow.Name
例如, DisplayMemberPath
只是數據模板的快捷方式,看起來像
<TextBlock Text="{Binding DisplayMemberPathValue}" />
您最好添加一些簡單的東西,例如KeyValuePair<int,string>
或自定義類,甚至只是添加ComboBoxItem
comboBox1.SelectedValuePath = "Key";
comboBox1.DisplayMemberPath = "Value";
foreach (DataRow item in ds.Tables[0].Rows)
{
comboBox1.Items.Add(
new KeyValuePair<int,string>((int)item["ID"], row["Name"] as string));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.