zoukankan      html  css  js  c++  java
  • wpf之DataGrid绑定DataTable,其中DataGridComboBoxColumn双向绑定枚举enum

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

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

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

            xmlns:jz="clr-namespace:*****.Model;assembly=****"
        xmlns:utils="clr-namespace:*******.util" xmlns:core="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());
            }
        }
    }

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

  • 相关阅读:
    JavaEE——SpringMVC(11)--拦截器
    JavaEE——SpringMVC(10)--文件上传 CommonsMultipartResovler
    codeforces 460A Vasya and Socks 解题报告
    hdu 1541 Stars 解题报告
    hdu 1166 敌兵布阵 解题报告
    poj 2771 Guardian of Decency 解题报告
    hdu 1514 Free Candies 解题报告
    poj 3020 Antenna Placement 解题报告
    BestCoder5 1001 Poor Hanamichi(hdu 4956) 解题报告
    poj 1325 Machine Schedule 解题报告
  • 原文地址:https://www.cnblogs.com/usen521/p/13626889.html
Copyright © 2011-2022 走看看