How can I show the items of the List<string> Sections
as a Combobox
under the Sections field in a DataGrid myDataGrid.
List<string> Sections = new List<string> {"C50", "C40", "C30"};
Currently I'm using the below code to populate the rest of the fields in myDataGrid.
var data = from row in Building.Columns
select new
{
row.Id,
row.X,
row.Y,
row.StartElevation,
row.EndElevation,
row.FoundationHeight,
Sections = ""
};
myDataGrid.ItemsSource = data;
If you using AutoGenerateColumns="True"
you should using AutoGeneratingColumn
event ( msdn ).
XAML:
<DataGrid x:Name="myDataGrid" ItemsSource="{Binding}"
AutoGenerateColumns="True"
AutoGeneratingColumn="myDataGrid_AutoGeneratingColumn"/>
Code-behind:
private void myDataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
if (e.PropertyName == "Sections")
{
var cb = new DataGridComboBoxColumn();
cb.Header = "Sections";
cb.ItemsSource = new List<string> { "C50", "C40", "C30" };
cb.SelectedValueBinding = new Binding("Sections");
e.Column = cb;
}
}
Solution with AutoGenerateColumns="False"
:
XAML:
<DataGrid x:Name="myDataGrid" ItemsSource="{Binding}"
AutoGenerateColumns="False"
>
<DataGrid.Columns>
<DataGridTextColumn Header="Id" Binding="{Binding Id}" />
<DataGridTextColumn Header="X" Binding="{Binding X}" />
<DataGridTextColumn Header="Y" Binding="{Binding Y}" />
<DataGridTextColumn Header="StartElevation" Binding="{Binding StartElevation}" />
<DataGridTextColumn Header="EndElevation" Binding="{Binding EndElevation}" />
<DataGridTextColumn Header="FoundationHeight" Binding="{Binding FoundationHeight}" />
<DataGridComboBoxColumn x:Name="cbSections" Header="Sections" SelectedItemBinding="{Binding Sections}"/>
</DataGrid.Columns>
</DataGrid>
Code-behind:
...
{
...
myDataGrid.ItemsSource = data;
cbSections.ItemsSource = new List<string> { "C50", "C40", "C30" };
...
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.