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());
            }
        }
    }

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

  • 相关阅读:
    php-fpm: 某项目网站频繁出现503问题解决( WARNING: [pool www] server reached pm.max_children setting (50), consider raising it)
    spring mvc: rss(xml)输出
    spring mvc: json练习
    spring mvc: xml练习
    spring mvc:输出json,输出多个json
    phalcon: 目录分组后的acl权限控制
    spring mvc: xml生成
    spring mvc:视图解析器
    Python爬虫从入门到放弃(二十)之 Scrapy分布式原理
    Python爬虫从入门到放弃(十九)之 Scrapy爬取所有知乎用户信息(下)
  • 原文地址:https://www.cnblogs.com/usen521/p/13626889.html
Copyright © 2011-2022 走看看