【问题标题】:wpf how to bind to Listwpf如何绑定到List
【发布时间】:2014-02-13 15:43:11
【问题描述】:

我正在尝试将对象列表绑定到 DataGrid,但我得到了错误的值: 对象类:

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&lt;Attribute&gt; attributes

attributeDataGrid.ItemsSource = attributes;

当我绑定时,我得到一个名称列正确的网格 但是“ValueList”显示为“(Collection)”而不是字符串......

我应该如何绑定列表?

【问题讨论】:

  • 您可以添加您的 xaml 代码(至少 datagrid 部分)...?

标签: c# wpf data-binding


【解决方案1】:

Value 中覆盖的 ToString 方法不会被调用,因为 WPF 在第二列中显示 ValueList 的内容,即它显示 ValueList.ToString()。 您希望在第二列中看到什么? ValueList?中的值的逗号分隔列表?

【讨论】:

  • 你是对的,这正是没有调用 ToString() 方法的问题。我想用逗号分隔 - 正确的做法是什么?
  • 您需要编写一个转换器,可以将List&lt;Value&gt; 转换为string。请参阅documentation 了解更多信息。
【解决方案2】:

试试下面对我有用的东西。

在加载方法上写下面的代码

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>

希望这段代码 sn-p 对你有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多