简体   繁体   English

wpf如何绑定到List

[英]wpf how to bind to List

i'm trying to bound a list of object to DataGrid but i'm getting wrong value: the object class:我正在尝试将 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();
    }
}

and i'm having a list of objects: List<Attribute> attributes我有一个对象列表: List<Attribute> attributes

attributeDataGrid.ItemsSource = attributes;

when i bound i get a grid with name column correct but the "ValueList" shown as "(Collection)" instead of the string...当我绑定时,我得到一个名称列正确的网格,但“ValueList”显示为“(Collection)”而不是字符串......

how should i bound the List?我应该如何绑定列表?

Your overriden ToString method in Value is not called, because WPF displays the content of ValueList in your second column, ie it displays ValueList.ToString() .不会调用您在Value中覆盖的ToString方法,因为ValueList在您的第二列中显示 ValueList 的内容,即显示ValueList.ToString() What do you expect to see in the second column?您希望在第二列中看到什么? A comma separated list of the values in the ValueList ? ValueList中的值的逗号分隔列表?

Try below things it works for me.试试下面对我有用的东西。

On Load Method write below code在加载方法上写下面的代码

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;

On XAML file try below在 XAML 文件上尝试下面

    <DataGrid x:Name="dataGrid" AutoGenerateColumns="False" ItemsSource="{Binding}" >
        <DataGrid.Columns>
            <DataGridTextColumn Binding="{Binding value}" />
        </DataGrid.Columns>
    </DataGrid>

Hope this code snippet helps to you.希望此代码段对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM