【问题标题】:How to set string property value to the ComboBox control inside Datagrid?如何将字符串属性值设置为 Datagrid 中的 ComboBox 控件?
【发布时间】:2020-08-27 06:33:33
【问题描述】:

我的 WPF 项目中有一个 DataGrid。我绑定的模型具有string 类型的属性DataType。在正常显示模式下,我将其显示为:

<DataGridTemplateColumn.CellTemplate>
   <DataTemplate>
      <TextBlock Style="{StaticResource CellBlock}" Text="{Binding DataType}" ToolTip="{Binding DataType}"/>
    </DataTemplate>
</DataGridTemplateColumn.CellTemplate>

在编辑模式下,我需要在ComboBox 中填充enum,并将选定的组合框项目设置为来自string 模型属性Datatype 的项目,如果用户更改组合框中的值应该反映在模型中。 我怎样才能实现这些目标?

【问题讨论】:

    标签: c# wpf mvvm datagrid


    【解决方案1】:

    您不需要自定义单元格模板,DataGrid 有一个内置的DataGridComboBoxColumn。在正常模式下,它将值显示为文本,在编辑模式下,它显示ComboBox

    您必须公开enum 定义为集合的常量。您可以为其创建一个简单的MarkupExtension,它返回任何给定enum 类型的值。

    public class EnumValuesExtension : MarkupExtension
    {
       public Type Type { get; set; }
    
       public override object ProvideValue(IServiceProvider serviceProvider)
       {
          return Enum.GetValues(typeof(MyEnum));
       }
    }
    

    这是您的DataGrid 的示例。如您所见,您可以简单地使用标记扩展将组合框列的ItemsSource 绑定到您的enum 类型,此处为MyEnum

    <DataGrid ItemsSource="{Binding newItems}">
       <DataGrid.Columns>
          <DataGridComboBoxColumn ItemsSource="{local:EnumValues Type={x:Type local:MyEnum}}"
                                  SelectedItemBinding="{Binding DataType}"/>
       </DataGrid.Columns>
    </DataGrid>
    

    在您的模型中,将enum 类型用于DataType 属性。我认为将其公开为string 没有任何用处。上面的示例假设您使用的是 enum 类型,而不是 string

    但是,如果您真的依赖 string,您可以创建一个简单的 value converter

    public class StringToEnumConverter : IValueConverter
    {
       public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
       {
          return Enum.Parse((Type)parameter, (string)value);
       }
    
       public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
       {
          return value.ToString();
       }
    }
    

    这会将组合框列上的绑定更改为:

    <DataGridComboBoxColumn ItemsSource="{local:EnumValues Type={x:Type local:MyEnum}}"
                            SelectedItemBinding="{Binding DataType, Converter={StaticResource StringToEnumConverter}, ConverterParameter={x:Type local:MyEnum}}"/>
    

    【讨论】:

    • 第二种方法在哪里指定属性绑定(“Datatype”)?
    • @AmolShinde 有一个错字。我更正了,也是SelectedItemBinding
    猜你喜欢
    • 1970-01-01
    • 2014-05-30
    • 2014-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-12
    • 1970-01-01
    相关资源
    最近更新 更多