百度了快一天,沒結果,除了幾個原創的,都是復制粘貼的內容。
不想用別的笨辦法,於是腦洞大開,想出了我的辦法。
首先是前台代碼,與網上的比較類似:
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()); } } }
上班時間,寫的比較簡單,文中沒有提到的地方,比如一些格式轉換等,都比較簡單,少了會報錯,比較好改。