wpf之DataGrid綁定DataTable,其中DataGridComboBoxColumn雙向綁定枚舉enum

百度了快一天,沒結果,除了幾個原創的,都是複製粘貼的內容。ide

不想用別的笨辦法,因而腦洞大開,想出了個人辦法。spa

 

首先是前臺代碼,與網上的比較相似:code

        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】,要注意大小寫,被坑了一陣子。orm

接下來是百度不到的「核心科技」:xml

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

 

上班時間,寫的比較簡單,文中沒有提到的地方,好比一些格式轉換等,都比較簡單,少了會報錯,比較好改。blog

相關文章
相關標籤/搜索