walle walle - 1 year ago 35
C# Question

How to bind two different attributes to two different datacontexts WPF C#

I have a standard menu where the headers are bound to a list in one viewmodel, and i want to bind the command from another viewmodel. I want this to be able to change language in the application. I defined the menu like this:

<Menu DockPanel.Dock="Top" DataContext="{Binding MenuViewModel, Mode=OneWay, Source={StaticResource mainViewModel}}">

where MenuViewModel contains all the commands and another viewmodel called LanguageViewModel contains all the headers. I then have to define every MenuItem like this:

<MenuItem Command="{Binding Path=NewProjectCommand}">
<Label DataContext="{StaticResource languageViewModel}" Content="{Binding Path=Names[menu.project.addnode]}" />

Which means at least 5 lines of code just for one MenuItem, and the menu might contain over 30 MenuItems...
Is there any simpler way to do this? I was thinking about templates but don't know how i would do that.

Answer Source

If menu.project.addnode is a string key, the following works for me:

    Command="{Binding NewProjectCommand}"
    Header="{Binding Names[menu.project.addnode], Source={StaticResource languageViewModel}"

Here's the quickie test VM I used for the localization strings:

public class LanguageViewModel
    public Dictionary<string, string> Names { get; } = new Dictionary<string, string>
        { "menu.project.addnode", "Add New Node" }