使用DataTemplateSelector绑定到DataTemplate中枚举描述的多语言组合框



我正在做一些单独的部分已经讨论过了,但我很难把它们放在一起。我们有一个应用程序,它有很多插件,需要不同的输入参数,我正在尝试制作多语言的插件。我一直在开发一个动态GUI,它检查插件以创建一个输入参数数组,并使用DataTemplateSelector根据参数的类型选择正确的控件。对于枚举器,我们试图将本地化的显示名称绑定到组合框。StackOverflow上有很多关于如何进行枚举/组合框绑定的线程,但我找不到一个是多语言和动态的(数据模板或其他(。

Brian Lagunas有一篇很棒的博客文章,几乎让我们做到了:http://brianlagunas.com/localize-enum-descriptions-in-wpf.但是,他在XAML中静态绑定了枚举。我们有数百个枚举,并且一直在创建新的枚举。因此,我正在努力思考如何最好地实现更具活力的目标。在此过程中,我需要使用反射来计算枚举器的类型,并将其绑定到组合框,但我不太清楚在哪里、何时或如何。

我在这里上传了一个扩展示例:https://github.com/bryandam/Combo_Enum_MultiLingual.我会尽量把相关的部分包括在这里,但很难把它浓缩起来。

public partial class MainWindow : Window
{
public ObservableCollection<Object> InputParameterList { get; set; } = new ObservableCollection<Object>();
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
//Create an example input object.
InputParameter bitlocker_drive = new InputParameter();
bitlocker_drive.Name = "BitLocker Enabled";
bitlocker_drive.Type = typeof(String);
InputParameterList.Add(bitlocker_drive);
InputParameter bitlocker_status = new InputParameter();
bitlocker_status.Name = "Status";
bitlocker_status.Type = typeof(Status);
InputParameterList.Add(bitlocker_status);
InputParameter bitlocker_foo = new InputParameter();
bitlocker_foo.Name = "Foo";
bitlocker_foo.Type = typeof(Foo);
InputParameterList.Add(bitlocker_foo);
}
}

这是我的XAML:

<Window x:Class="BindingEnums.MainWindow"
....
<Window.Resources>        
...
<DataTemplate x:Key="ComboBox">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding Name, Mode=TwoWay}" />
<ComboBox ItemsSource="{Binding Source={local:EnumBindingSource {x:Type local:Status}}}" Grid.Column="1"/>                
</Grid>
</DataTemplate>
...
<local:InputParameterTemplateSelector x:Key="InputDataTemplateSelector" Checkbox="{StaticResource Checkbox}" ComboBox="{StaticResource ComboBox}" DatePicker="{StaticResource DatePicker}" TextBox="{StaticResource TextBox}"/>
</Window.Resources>
<Grid>
<ListBox Name="InputParameters" KeyboardNavigation.TabNavigation="Continue" HorizontalContentAlignment="Stretch" ItemsSource="{Binding InputParameterList}"  ScrollViewer.HorizontalScrollBarVisibility="Disabled" ScrollViewer.VerticalScrollBarVisibility="Auto" Background="Transparent" BorderBrush="Transparent" ItemTemplateSelector="{StaticResource InputDataTemplateSelector}">
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="IsTabStop" Value="False" />
<Setter Property="HorizontalContentAlignment" Value="Stretch" />
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
</Grid>

下面是我正在测试的两个枚举示例:

[TypeConverter(typeof(EnumDescriptionTypeConverter))]
public enum Status
{        
[Display(Name = nameof(Resources.EnumResources.Good), ResourceType = typeof(Resources.EnumResources))]
Good,
[Display(Name = nameof(Resources.EnumResources.Better), ResourceType = typeof(Resources.EnumResources))]
Better,
Best
}
[TypeConverter(typeof(EnumDescriptionTypeConverter))]
public enum Foo
{
[Display(Name = nameof(Resources.EnumResources.Foo), ResourceType = typeof(Resources.EnumResources))]
Foo,
[Display(Name = nameof(Resources.EnumResources.Bar), ResourceType = typeof(Resources.EnumResources))]
Bar
}

这是枚举类型转换器:

public class EnumDescriptionTypeConverter : EnumConverter
{
public EnumDescriptionTypeConverter(Type type)
: base(type)
{}
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
{
if (destinationType == typeof(string))
{
if (value != null)
{
FieldInfo fi = value.GetType().GetField(value.ToString());
if (fi != null)
{
//Reflect into the value's type to get the display attributes.
FieldInfo fieldInfo = value.GetType().GetField(value.ToString());
DisplayAttribute displayAttribute = fieldInfo?
.GetCustomAttributes(false)
.OfType<DisplayAttribute>()
.SingleOrDefault();
if (displayAttribute == null)
{
return value.ToString();
}
else
{
//Look up the localized string.
ResourceManager resourceManager = new ResourceManager(displayAttribute.ResourceType);                            
string name = resourceManager.GetString(displayAttribute.Name);
return string.IsNullOrWhiteSpace(name) ? displayAttribute.Name : name;
}
}
}
return string.Empty;
}
return base.ConvertTo(context, culture, value, destinationType);
}

这是Enum绑定源标记扩展:

public class EnumBindingSourceExtension : MarkupExtension
{
...
public override object ProvideValue(IServiceProvider serviceProvider)
{
if (null == this._enumType)
throw new InvalidOperationException("The EnumType must be specified.");
Type actualEnumType = Nullable.GetUnderlyingType(this._enumType) ?? this._enumType;
Array enumValues = Enum.GetValues(actualEnumType);
if (actualEnumType == this._enumType)
return enumValues;
Array tempArray = Array.CreateInstance(actualEnumType, enumValues.Length + 1);
enumValues.CopyTo(tempArray, 1);
return tempArray;
}
}

同样,我的目标是找出如何避免静态绑定到单个枚举类型(如下面的XAML(,而是基于输入参数的任何类型进行绑定:

<ComboBox ItemsSource="{Binding Source={local:EnumBindingSource {x:Type local:Status}}}" Grid.Column="1"/

我曾在Window代码隐藏、数据模板选择器甚至自定义控件中尝试过,但都没有取得太大成功。我的第一个"真正的"WPF应用程序,所以我确实有点不适合把所有这些放在一起,而不是放在各自的部分。

以下是运行的示例

一个可能的"解决方案"是完全放弃使用枚举进行本地化。这就是我所做的,它允许我自己和项目中的其他开发人员在我们的XAML中插入纯英语,就像这样:

<TextBlock Text="{Translate 'Scanning Passport'}" />

我写了一个小实用程序来扫描我们的XAML文件,并将这些文件的所有实例提取到Excel电子表格中,然后发送给翻译人员,第二个实用程序将我们得到的翻译带回并打包到XML文件中(每种语言一个(。这些文件基本上是字典,XAML中的英文文本用作关键字,以查找当前所选语言的翻译:

<Translation key="Scan Passport" text="扫描护照" />

这有很多好处:

  • 开发人员仍然用通用语言(在我的例子中是英语(编写XAML
  • 您不必每次在前端添加新文本时都重新构建解决方案中的每个项目
  • 如果添加尚未翻译的新文本,则"Translate"扩展名正好回到英语翻译
  • XML文件存储在本地,因此客户端可以随意更改本地化文本(包括英语(
  • 您可以完全控制GUI中哪些字段进行翻译,哪些字段不进行翻译

当然,如果您在运行时更改翻译,那么正在翻译的控件都会自动更新并立即切换到新语言。

显然,这个系统的关键是编写"翻译"自定义标记扩展,幸运的是,有人已经为您完成了这项工作:

https://www.wpftutorial.net/LocalizeMarkupExtension.html

好的,花了几天的时间进行了黑客攻击,但我终于明白了。在MarkupExtensions的ProviderValue调用中,您可以获取IProvideValueTarget服务来获取目标。这允许你做两件事。首先,您可以检查目标是否为null,从而绕过初始启动调用并延迟绑定,直到应用数据模板。其次,一旦应用了模板,您就可以获得对象的数据上下文,从而可以反映到它中,从而消除在设计时声明它的需要(我的最终目标(。

这是我的MarkupExtension类的ProviderValue函数:

public override object ProvideValue(IServiceProvider serviceProvider)
{
//Get the target control
var pvt = (IProvideValueTarget)serviceProvider.GetService(typeof(IProvideValueTarget));
if (pvt == null) { return null; }
var target = pvt.TargetObject as FrameworkElement;
//If null then return the class to bind at runtime.
if (target == null) { return this; }
if (target.DataContext.GetType().IsEnum)
{
Array enumValues = Enum.GetValues(target.DataContext.GetType());
return enumValues;                
}
return null;
}

最终的结果是,我可以指定combobox项目源,而无需指定单个静态类型:

<ComboBox ItemsSource="{local:EnumBindingSource}"

最新更新