以编程方式创建WPF DataGrid列而不是绑定

时间:2016-01-17 10:39:50

标签: c# wpf xaml datagrid

我的Xaml看起来像这样:

<DataGrid Name="gridBasket" AutoGenerateColumns="False">
   <DataGrid.Columns>
      <DataGridTextColumn Binding="{Binding BasketName}">
      </DataGridTextColumn>
   </DataGrid.Columns>
</DataGrid>

我的班级看起来像:

public class Fruit
{
    public int FruitId { get; set; }
    public string FruitName { get; set; }
    public int FruitCount { get; set; }
 }

public class Basket
{
    public int BasketId { get; set; }
    public string BasketName { get; set; }
    public ObservableCollection<Fruit> Fruits { get; set; }
}

public class Shop
{
    public static ObservableCollection<Basket> Bind()
    {
        return new ObservableCollection<Basket>
        {
            new Basket { BasketId = 1, BasketName = "Gold",
                Fruits = new ObservableCollection<Fruit>
                {
                    new Fruit { FruitId = 1, FruitName = "Oranges", FruitCount = 10 },
                    new Fruit { FruitId = 2, FruitName = "Apples", FruitCount = 8 },
                    new Fruit { FruitId = 3, FruitName = "Bananas", FruitCount = 6 }
                }
            },
            new Basket { BasketId = 2, BasketName = "Silver",
                Fruits = new ObservableCollection<Fruit>
                {
                    new Fruit { FruitId = 1, FruitName = "Oranges", FruitCount = 5 },
                    new Fruit { FruitId = 2, FruitName = "Apples", FruitCount = 4 },
                    new Fruit { FruitId = 3, FruitName = "Bananas", FruitCount = 3 }
                }
            }
        };
    }
}

在我的代码背后,我尝试动态添加列,并将这些动态列的绑定设置为嵌套集合属性。

private void LoadData()
{
    gridBasket.AutoGenerateColumns = false;

    ObservableCollection<DemoBEL.Basket> bColl = DemoBEL.Shop.Bind();
    gridBasket.ItemsSource = bColl;

    int i = 0;
    foreach (DemoBEL.Fruit fObj in bColl[0].Fruits)
    {
        gridBasket.Columns.Add(AddColumn(i, fObj.FruitName));
        i++;
    }
}

private DataGridTextColumn AddColumn(int i, string propName)
{
    DataGridTextColumn tc = new DataGridTextColumn();
    tc.Header = propName;
    String binding = String.Format("{{Binding Path=Fruits[{0}].{1}}}", 0, "FruitCount");
    Binding tcBinding = new Binding(binding);
    tc.Binding = tcBinding;
    return tc;
}
计数空无一人。但是,如果我将相同的绑定与固定值放在一起,则计数开始出现。我应该做些什么改变,使每个水果的计数开始出现在标题中指定水果下的数据网格中。

Cells are blank

1 个答案:

答案 0 :(得分:2)

假设您已在视图上设置了正确的DataContext,则您在Binding构造函数中使用的路径不正确。您只需要将属性名称/路径传递给Binding构造函数。您不需要使用{Binding}传递带格式的字符串,而只需要在AddColumn方法中执行所有操作。

将您的AddColumn方法更新为以下内容:

private DataGridTextColumn AddColumn(int i, string propName)
{
    DataGridTextColumn tc = new DataGridTextColumn();
    tc.Header = propName;
    Binding tcBinding = new Binding(string.Format("Fruits[{0}].FruitCount", i));
    tc.Binding = tcBinding;
    return tc;
}

请参阅BindingData Binding Overview上的这些MSDN页面,以便更好地了解DataBinding。

以下是更改AddColumn方法后的输出:

enter image description here