[英]wpf how to bind to List
我正在嘗試將 object 列表綁定到 DataGrid,但我得到了錯誤的值:object class:
public class Attribute
{
public Attribute()
{
}
private string _name;
public string name
{
get { return _name; }
set { _name = value; }
}
private List<Value> _valueList = new List<Value>();
public List<Value> ValueList
{
get { return _valueList; }
set { _valueList = value; }
}
}
public class Value
{
private string _value;
public string value
{
get { return _value; }
set { _value = value; }
}
public override string ToString()
{
return _value.ToString();
}
}
我有一個對象列表: List<Attribute> attributes
attributeDataGrid.ItemsSource = attributes;
當我綁定時,我得到一個名稱列正確的網格,但“ValueList”顯示為“(Collection)”而不是字符串......
我應該如何綁定列表?
不會調用您在Value
中覆蓋的ToString
方法,因為ValueList
在您的第二列中顯示 ValueList 的內容,即顯示ValueList.ToString()
。 您希望在第二列中看到什么? ValueList
中的值的逗號分隔列表?
試試下面對我有用的東西。
在加載方法上寫下面的代碼
Attribute atr = new Attribute();
atr.ValueList.Add(new Value() { value = "One" });
atr.ValueList.Add(new Value() { value = "Two" });
atr.ValueList.Add(new Value() { value = "Three" });
atr.ValueList.Add(new Value() { value = "Four" });
dataGrid.DataContext = atr.ValueList;
在 XAML 文件上嘗試下面
<DataGrid x:Name="dataGrid" AutoGenerateColumns="False" ItemsSource="{Binding}" >
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding value}" />
</DataGrid.Columns>
</DataGrid>
希望此代碼段對您有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.