【发布时间】:2020-02-04 21:30:36
【问题描述】:
我正在尝试使用名为 MachineComponentFault 的自定义类的 ObservableCollection 创建一个 Treeview,该类包含一个名为 FaultText 的字符串属性,我想让文本本地化。
我正在使用来自 Codeproject 的 WPF Runtime Localization 在运行时本地化文本,它通常工作如下:
<TextBlock Text="{Binding Path=NameInResources, Source={StaticResource Resources}}"/>
问题是我似乎无法弄清楚如何将属性的值设置为路径,以便它可以检索翻译。这是我迄今为止所管理的:
<TreeView Name="myTreeView" VirtualizingPanel.IsVirtualizing="True" ItemsSource="{Binding Faults}">
<TreeView.Resources>
<DataTemplate DataType="{x:Type MassComponents:MachineComponentFault}">
<StackPanel Orientation="Horizontal" >
<TextBlock Name="Text1" Text="{Binding FaultText}"/>
<TextBlock Name="Text2" Text="{Binding Path=FLT_PTC_1, Source={StaticResource Resources}}"/>
</StackPanel>
</DataTemplate>
</TreeView.Resources>
</TreeView>
本质上 Text1 在运行时显示 FLT_PTC_1,而 Text2 显示“电机过热”,这是 Resources.resx(可以翻译)中 FLT_PTC_1 的值。问题是我似乎无法使用 FaultText 属性完成 Text2 所做的事情。
有办法吗?
编辑:
使用 mm8 解决方案解决它,同时保持 WPF 运行时本地化。解决方案一点也不漂亮,因为它包括在一个虚拟类上创建一个 Binding,然后将绑定值作为字符串检索,这似乎有点令人费解,但这是我能找到的最佳解决方案。
public class ResourceConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
string resourceName = value as string;
if (!string.IsNullOrEmpty(resourceName)) //look up the resource here:
{
Binding b = new Binding(resourceName); //Create Binding using as Path the value of FaultText
b.Source = CultureResources.ResourceProvider; //Get the resources from WPF Runtime Localization ObjectDataProvider
BindingOperations.SetBinding(_dummy, Dummy.ValueProperty, b); //Set the Binding to the dummy class instance
return _dummy.GetValue(Dummy.ValueProperty); //Retrieve the value of the Binding from the dummy class instance and return it
}
return value;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
//Initialize Dummy class
private static readonly Dummy _dummy = new Dummy();
//Create a dummy class that accepts the Binding
private class Dummy : DependencyObject
{
public static readonly DependencyProperty ValueProperty =
DependencyProperty.Register("Value", typeof(object), typeof(Dummy), new UIPropertyMetadata(null));
}
}
XAML 与建议的 mm8 相同。
【问题讨论】: