开发者

WPF Localized TreeView with HierarchicalDataTemplate

Here's the thing:

I have a simple WPF Windows application, in which I've included a TreeView, which is being constructed with the help of HierarchicalDataTemplate and fed with some hierarchical data.

The hierarchical data structure is made of FakeRec class, which contains child items in a List<FakeRec>. Each item contains a Title string property. So in my XAML, I have:

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

This works fine, and in the generated TreeView I see the title of each node.

Now I want to make this whole tree localizable. I have my resources in FakeDirResources.Resx (in a separate assembly, but that does not matter). If I do this:

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

My tree is blank (obviously, because in my FakeDirResources.resx file I don't have a resource with key Title, but I need to use the Title of the other binding, resolve it through the resources, and then somehow bind the result to the tree.

Note that if i just place a TextBlock on the window, without relation to the tree or to the HierarchicalDataTemplate, I can bind it without problem to the resources, like so:

<TextBloc开发者_如何学Gok Text="{Binding Path=games, Source={StaticResource FakeDirResources}}"/>;

This works great, fetching the string, and if I change the System.Threading.Thread.CurrentThread.CurrentUICulture and refresh my provider, this string gets changed to to the new language.

The question is how do I combine the two? What am I missing? I guess there has to be some trick (and with my short experience with WPF it's probably not a straight-forward trick).

Cheers!

Alon.


Potentially you could work through this with an 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
}

Used like so:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜