2020年9月7日星期一

wpf之DataGrid绑定DataTable,其中DataGridComboBoxColumn双向绑定枚举enum

百度了快一天,没结果,除了几个原创的,都是复制粘贴的内容。

不想用别的笨办法,于是脑洞大开,想出了我的办法。

 

首先是前台代码,与网上的比较类似:

      "clr-namespace:*******.util"  ="clr-namespace:System;assembly=mscorlib"  mc:Ignorable="d"  Title="数据项管理" Height="500" Width="700" Name="window" WindowStartupLocation="CenterScreen" WindowStyle="ToolWindow"> <Window.Resources>  <utils:SoftDataFormatConverter x:Key="SoftDataFormatConverter"/>  <ObjectDataProvider x:Key="SoftDataFormatEnumKey" MethodName="GetValues" ObjectType="{x:Type core:Enum}">   <ObjectDataProvider.MethodParameters>    <x:Type Type="jz:SoftDataFormat"/>   </ObjectDataProvider.MethodParameters>  </ObjectDataProvider> </Window.Resources>

<DataGridComboBoxColumn Header="数据类型" ItemsSource="{Binding Source={StaticResource SoftDataFormatEnumKey}}" SelectedItemBinding="{Binding SoftDataFormat, Converter={StaticResource SoftDataFormatConverter}, Mode=TwoWay}"/>

我的DataGrid绑定的是DataTable,然后,DataGridComboBoxColumn 绑定中的 【SelectedItemBinding="{Binding SoftDataFormat】,要注意大小写,被坑了一阵子。

接下来是百度不到的“核心科技”:

namespace *****.util{ [ValueConversion(typeof(int), typeof(SoftDataFormat))] public class SoftDataFormatConverter : IValueConverter {  public object Convert(object value, Type targetType, object parameter, CultureInfo culture)  {   if (int.TryParse(value.ToString(), out int vInt))   {    return (SoftDataFormat)vInt;   }   else   {    return (SoftDataFormat)Enum.Parse(typeof(SoftDataFormat), value.ToString());   }  }  public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)  {    return (int)(SoftDataFormat)Enum.Parse(typeof(SoftDataFormat), value.ToString());  } }}

 

上班时间,写的比较简单,文中没有提到的地方,比如一些格式转换等,都比较简单,少了会报错,比较好改。

wpf之DataGrid绑定DataTable,其中DataGridComboBoxColumn双向绑定枚举enum贝贝官网Listing优化细节要点Vendor Express 玩法详解(上)饱受争议的Amazon's Choice小蓝标,运作内幕即将揭底!平台重品牌的环境下,要不要加入亚马逊自有品牌项目?亚马逊运营中如何打造爆款?螺旋式上升打造法详解!印度B2B电商的发展现状:AI和机器学习是最看重的科技2019年下半场,卖家如何实现运营突破?

没有评论:

发表评论