我正在尝试创建一个DataGrid,其中一行是列标题,然后是另外10行,每列填充组合框。例如:
<DataGrid AutoGenerateColumns="False"
Name="dataGrid1">
<DataGrid.Columns>
<DataGridComboBoxColumn Header="Products"
SelectedValueBinding="{Binding ProductName}">
<DataGridComboBoxColumn.ElementStyle>
<Style TargetType="ComboBox">
<Setter Property="ItemsSource" Value="{Binding Path=ProductNamesList,
RelativeSource={RelativeSource AncestorType={x:Type Window}}}"/>
</Style>
</DataGridComboBoxColumn.ElementStyle>
<DataGridComboBoxColumn.EditingElementStyle>
<Style TargetType="ComboBox">
<Setter Property="ItemsSource" Value="{Binding Path=ProductNamesList,
RelativeSource={RelativeSource AncestorType={x:Type Window}}}"/>
</Style>
</DataGridComboBoxColumn.EditingElementStyle>
</DataGridComboBoxColumn>
<DataGridComboBoxColumn Header="Amount" />
<DataGridComboBoxColumn Header="Units" />
</DataGrid.Columns>
</DataGrid>
现在,我需要10行3个组合框。我试过Google,但是我的Google-Fu让我失望了,因为我发现我告诉我将行绑定到列表中。我想要的是什么?或者我应该找另一种方式?
编辑1
我想问的是,一旦有了这个,我怎么能填充10行3个组合框?每列在框中都有相同的项目。
编辑2
我编辑过来表明我添加了Jim的代码。但是,如果我创建一个ProductNamesList
,并用10个项目填充它,并将其绑定到我的列,我会得到10行空框。
编辑3
这是List<string>
:
var ProductNamesList = new List<string>();
var test1 = "test1";
var test2 = "test2";
var test3 = "test3";
var test4 = "test4";
var test5 = "test5";
var test6 = "test6";
var test7 = "test7";
var test8 = "test8";
var test9 = "test9";
var test10 = "test10";
ProductNamesList.Add(test1);
ProductNamesList.Add(test2);
ProductNamesList.Add(test3);
ProductNamesList.Add(test4);
ProductNamesList.Add(test5);
ProductNamesList.Add(test6);
ProductNamesList.Add(test7);
ProductNamesList.Add(test8);
ProductNamesList.Add(test9);
ProductNamesList.Add(test10);
grid1.ItemsSource = ProductNamesList;
答案 0 :(得分:1)
只需将组合框列的元素和编辑样式绑定到列表中即可。此示例将其绑定到window.cs文件中的列表。
public partial class MainWindow : Window
{
public List<string> ProductNamesList { get; set; }
public MainWindow()
{
InitializeComponent();
ProductNamesList = new List<string>();
ProductNamesList.Add("Hamburger");
ProductNamesList.Add("Uranium");
ProductNamesList.Add("Toothbrush");
}
}
<DataGridComboBoxColumn Header="Products"
SelectedValueBinding="{Binding ProductName}">
<DataGridComboBoxColumn.ElementStyle>
<Style TargetType="ComboBox">
<Setter Property="ItemsSource" Value="{Binding Path=ProductNamesList,
RelativeSource={RelativeSource AncestorType={x:Type Window}}}"/>
</Style>
</DataGridComboBoxColumn.ElementStyle>
<DataGridComboBoxColumn.EditingElementStyle>
<Style TargetType="ComboBox">
<Setter Property="ItemsSource" Value="{Binding Path=ProductNamesList,
RelativeSource={RelativeSource AncestorType={x:Type Window}}}"/>
</Style>
</DataGridComboBoxColumn.EditingElementStyle>
</DataGridComboBoxColumn>