【问题标题】:WPF Localized TreeView with HierarchicalDataTemplate带有 HierarchicalDataTemplate 的 WPF 本地化 TreeView
【发布时间】:2011-02-15 19:44:49
【问题描述】:

事情是这样的:

我有一个简单的 WPF Windows 应用程序,其中包含一个 TreeView,它是在 HierarchicalDataTemplate 的帮助下构建的,并提供了一些分层数据。

分层数据结构由 FakeRec 类组成,该类包含List<FakeRec> 中的子项。每个项目都包含一个 Title 字符串属性。 所以在我的 XAML 中,我有:

...
<HierarchicalDataTemplate ItemsSource="{Binding Items}" DataType="{x:Type local:FakeRec}">
...
     <TextBlock Grid.Column="0" Text="{Binding Path=Title}"/>
...
</HierarchicalDataTemplate>
...

这很好用,在生成的TreeView 中我看到了每个节点的标题。

现在我想让整个树可本地化。 我在 FakeDirResources.Resx 中有我的资源(在一个单独的程序集中,但这没关系)。 如果我这样做:

...
<HierarchicalDataTemplate ItemsSource="{Binding Items}" DataType="{x:Type local:FakeRec}">
...
    <TextBlock Grid.Column="0" Text="{Binding Path=Title, Source={StaticResource FakeDirResources}}"/>
...
</HierarchicalDataTemplate>
...

我的树是空白的(很明显,因为在我的FakeDirResources.resx文件中我没有键为Title的资源,但是我需要使用另一个绑定的Title,通过资源来解决,然后以某种方式将结果绑定到树。

请注意,如果我只是在窗口上放置一个TextBlock,与树或HierarchicalDataTemplate 无关,我可以毫无问题地将它绑定到资源,如下所示:

<TextBlock Text="{Binding Path=games, Source={StaticResource FakeDirResources}}"/>;

这很好用,获取字符串,如果我更改 System.Threading.Thread.CurrentThread.CurrentUICulture 并刷新我的提供程序,此字符串将更改为新语言。

问题是如何将两者结合起来?我错过了什么? 我想一定有一些技巧(根据我对 WPF 的短暂经验,这可能不是一个直截了当的技巧)。

干杯!

阿隆。

【问题讨论】:

  • 我知道Title 包含进入FakeDirResources 的密钥吗?

标签: wpf xaml binding localization hierarchicaldatatemplate


【解决方案1】:

您可以通过IValueConverter 解决这个问题:

public class KeyResourceConverter : IValueConverter
{
    #region IValueConverter Members

    public object Convert(object value, Type targetType,
        object parameter, CultureInfo culture)
    {
        var key = System.Convert.ToString(value);
        var lookup = parameter as ResourceManager;

        return lookup.GetString(key, culture);
    }

    public object ConvertBack(object value, Type targetType,
        object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }

    #endregion
}

这样使用:

<TextBlock Text="{Binding Path=Title,
                          Converter={StaticResource keyResource}
                          ConverterParameter={x:Static local:FakeDirResources.ResourceManager}}"
           />

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    相关资源
    最近更新 更多