WPF Datagrid绑定不适用于嵌套对象列表

时间:2016-05-25 20:48:19

标签: c# wpf binding datagrid

我有WPF DataGrid:

<DataGrid x:Name="dataGrid" Margin="0,18,0,0" AutoGenerateColumns="False" CanUserAddRows="True" CanUserDeleteRows="True" HeadersVisibility="Column" InitializingNewItem="dataGrid_InitializingNewItem"/>

由于某些原因,我必须实现C#代码的结合:

// seems like it isn't important wthat is _attributeTypeSet
_attributeTypeSet = attributeTypesSet;

dataGrid.Columns.Clear();

DataGridCheckBoxColumn isUseColumn = new DataGridCheckBoxColumn()
{
    Binding = new Binding("IsUse")
};
dataGrid.Columns.Add(isUseColumn);

for (int i = 0; i < _attributeTypeSet.PredictiveAttributeTypes.Count; i++)
{
    DataGridComboBoxColumn predictiveAttributeTypeColumn = new DataGridComboBoxColumn()
    {
        ItemsSource = _attributeTypeSet.PredictiveAttributeTypes[i].Values,
        // this is how I set bunding path for enumerable property, and it works
        TextBinding = new Binding("PredictiveAttributeValues[" + i + "]"),
    };
    dataGrid.Columns.Add(predictiveAttributeTypeColumn);
}

DataGridComboBoxColumn decisiveAttributeValueColumn = new DataGridComboBoxColumn()
{
    ItemsSource = _attributeTypeSet.DecisiveAttributeType.Values,
    TextBinding = new Binding("DecisiveAttributeValue"),
};
dataGrid.Columns.Add(decisiveAttributeValueColumn);

_items = new List<ArguedLearningExamplesDataGridItem>();
dataGrid.ItemsSource = _items;

我有这样的视图模型类:

public class ArguedLearningExamplesDataGridItem
{
    public bool IsUse { get; set; }
    // the property below works
    public List<string> PredictiveAttributeValues { get; set; }
    public string DecisiveAttributeValue { get; set; }

    public ArguedLearningExamplesDataGridItem()
    {
        IsUse = true;
        PredictiveAttributeValues = new List<PredictiveAttributeValue>();
    }
}

此代码效果很好。

我将属性PredictiveAttributeValues修改为:

public List<PredictiveAttributeValue> PredictiveAttributeValues { get; set; }

其中PredictiveAttributeValue为:

public class PredictiveAttributeValue
{
    public string Value { get; set; }
    public bool IsBecauseExpression { get; set; }
    public bool IsDespiteExpression { get; set; }

    public PredictiveAttributeValue()
    { }

    public PredictiveAttributeValue(string value, bool isBecauseExpression, bool isDespiteExpression)
    {
        Value = value;
        IsBecauseExpression = isBecauseExpression;
        IsDespiteExpression = isDespiteExpression;
    }
}

所以PredictiveAttributeValue成为对象列表而不是字符串列表。

我也修改了绑定:

TextBinding = new Binding("PredictiveAttributeValues[" + i + "].Value")

并得到下一个结果:在dataGrid中,我看到了我在ArguedLearningExamplesDataGridItem的构造函数中设置的所有内容,但是对于dataGrid.Items,视觉控制中没有任何变化。所以,我猜,绑定不起作用。有什么问题?

我读了一篇名为“Binding.Path Property”的msdn文章,并按照那里写的那样做了。

0 个答案:

没有答案