简体   繁体   English

如果绑定到的DataTable具有项目列表,如何在DataGrid中显示ComboBox?

[英]How to display a ComboBox in a DataGrid if the DataTable it is bound to has a list of items?

I have a DataSet. 我有一个数据集。 I don't know the contents of the set. 我不知道布景的内容。 I just have to display a table of the set in a DataGrid. 我只需要在DataGrid中显示集合的表即可。 I'm able to do this using the following code. 我可以使用以下代码来做到这一点。 Just to able to work with it, I have created my own DataSet. 为了能够使用它,我创建了自己的数据集。 CustomerDataProvider is the class I have created that has a method that returns a dummy DataSet. CustomerDataProvider是我创建的类,该类具有一种返回伪DataSet的方法。

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>

Now, if the DataTable contains a bool value, the DataGrid automatically displays a CheckBox. 现在,如果DataTable包含布尔值,则DataGrid将自动显示一个CheckBox。 I want to be able to automatically display a ComboBox if the DataTable contains a List of items. 如果DataTable包含项目列表,我希望能够自动显示ComboBox。 How do I go about achieving this? 我该如何实现这一目标?

Instead of auto-generating columns, set AutoGenerateColumns to false, you can define the columns and bind with different fields of the DataTable . 代替自动生成列,可以将AutoGenerateColumns设置为false,您可以定义列并与DataTable不同字段绑定。 You can take DataGridTemplateColumn and provide the CellTemplate for the same. 您可以使用DataGridTemplateColumn并为其提供CellTemplate See the reference code below: 请参阅下面的参考代码:

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

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

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