【问题标题】:How to display a ComboBox in a DataGrid if the DataTable it is bound to has a list of items?如果绑定的 DataTable 具有项目列表,如何在 DataGrid 中显示 ComboBox?
【发布时间】:2015-07-27 04:03:29
【问题描述】:

我有一个数据集。我不知道套装的内容。我只需要在 DataGrid 中显示该集合的表。我可以使用以下代码来做到这一点。为了能够使用它,我创建了自己的数据集。 CustomerDataProvider 是我创建的具有返回虚拟数据集的方法的类。

CustomerDataProvider provider = new CustomerDataProvider();
DataSet ds = new DataSet();
DataTable table = new DataTable();
DataView view = new DataView();



    public MainWindow()
    {
        InitializeComponent();
        ds = dataset.GetDataSet();
        table = ds.Tables[0];
        view = table.AsDataView();
        this.DataContext = view;
    }


<Grid>
    <DataGrid x:Name="dynamicGrid" ItemsSource="{Binding Path=., Mode=TwoWay}" ColumnWidth="*"  />
</Grid>

现在,如果 DataTable 包含一个 bool 值,DataGrid 会自动显示一个 CheckBox。如果 DataTable 包含项目列表,我希望能够自动显示 ComboBox。我该如何实现这一目标?

【问题讨论】:

  • 你要找的是DataTemplate

标签: c# wpf datagrid combobox datatable


【解决方案1】:

除了自动生成列,将AutoGenerateColumns 设置为false,您可以定义列并与DataTable 的不同字段绑定。您可以使用DataGridTemplateColumn 并提供CellTemplate 相同的。请参阅下面的参考代码:

  <DataGrid AutoGenerateColumns="False">
    <DataGridTemplateColumn>
      <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
          <ComboBox />
        </DataTemplate>
      </DataGridTemplateColumn.CellTemplate>
    </DataGridTemplateColumn>
  </DataGrid>

【讨论】:

  • 谢谢。但我无法定义列,因为我不知道 DataTable 将包含什么。每次我打开应用程序时,内容都会发生变化。
猜你喜欢
  • 2016-11-30
  • 2021-03-09
  • 2015-10-04
  • 2011-04-07
  • 2014-09-12
  • 2010-11-07
  • 1970-01-01
  • 2015-06-23
  • 1970-01-01
相关资源
最近更新 更多