WPF DataGrid how to set ColumnType for another type based on related data?

I have a Preferences data structure, where I have a Value field and an enumeration for the Type field.

The type can be 0-Boolean, 1-Integer, 2-String ...

Depending on the value in this Type field, I would like to display the Value cell in different ways, a check box, a text box, a drop-down list, etc. So, to make this clear, different cells should be displayed in the same column depending on the data in this row.

I suppose I need to use a DataGridTemplateColumn, but I have never done this and would like, if possible, an example.

Also, what can I do with XAML and what needs to be done in Code? I think the value converter should also be used?

+7
source share
1 answer
<DataGrid ItemsSource="{Binding Items,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" > <DataGrid.Columns> <DataGridTemplateColumn> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <ContentControl x:Name="content" Content="{Binding}" > </ContentControl> <DataTemplate.Triggers> <DataTrigger Binding="{Binding ItemType}" Value="0"> <Setter TargetName="content" Property="ContentTemplate"> <Setter.Value> <DataTemplate> <CheckBox IsChecked="{Binding Value,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"></CheckBox> </DataTemplate> </Setter.Value> </Setter> </DataTrigger> <DataTrigger Binding="{Binding ItemType}" Value="1"> <Setter TargetName="content" Property="ContentTemplate"> <Setter.Value> <DataTemplate> <TextBox Text="{Binding Value,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"></TextBox> </DataTemplate> </Setter.Value> </Setter> </DataTrigger> </DataTemplate.Triggers> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> </DataGrid.Columns> </DataGrid> 

In CodeBehind, you have ObservableCollection {get; set;}

public class SimpleClass {public TypeEnum ItemType {get; set;} public object Value {get; set;}}

+8
source

All Articles