WPF DataGrid如何根据绑定数据将ColumnType设置为不同类型? [英] WPF DataGrid how to set ColumnType to different type based on bound data?
问题描述
我具有首选项数据结构,其中有字符串 Value字段和 Type字段的枚举。
I have "Preferences" data structure where I have string "Value" field and enum for "Type" field.
类型可以是0-布尔值,1-整数,2-String ...
Type can be 0-Boolean, 1-Integer, 2-String ...
根据此Type字段中的值,我想以不同的方式显示 Value单元格Checkbox,Textbox,下拉菜单等。因此,为了清楚起见-同一列应根据该行中的数据显示不同的单元格。
Depending on value in this Type field I'd like to display "Value" cell different way Checkbox, Textbox, dropdown, etc. So, to make it clear - same column should display different cells depending on data in that row..
我想我需要使用DataGridTemplateColumn,但我从未这样做过,并且会尽可能举一些例子。
I guess I need to employ DataGridTemplateColumn but I never did that and would like some example if possible.
此外,我可以使用XAML做什么以及需要用Code做什么?我想还必须使用值转换器吗?
Also, what can I do with XAML and what needs to be done in Code? I guess Value converter will have to be used as well?
推荐答案
<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>
在代码后面,您有一个ObservableCollection Items {get; set;}
In CodeBehind you have a ObservableCollection Items {get;set;}
公共类SimpleClass
{
public TypeEnum ItemType {get; set;}
公共对象值{get; set;}
}
public class SimpleClass { public TypeEnum ItemType{get;set;} public object Value {get;set;} }
这篇关于WPF DataGrid如何根据绑定数据将ColumnType设置为不同类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!