Search code examples
c#wpfxamlmvvm

Pass Variable from parent to child in a hybrid WPF MVVM-usercontrol schema


I have a program with the following schema.

The program starts with a login, once the user puts the name and password it directs to the main window (no problem passing the values there as it is between forms). This windows uses a MVVM schema to load the ContentControl necessary in that moment.

<Window.Resources>
    <DataTemplate ...>
    </DataTemplate>  (several times)
</Window.Resources>
<DockPanel>
    <Menu DockPanel.Dock="Top" ItemsSource="{Binding MenuItems}">
        <Menu.ItemContainerStyle>
            <Style TargetType="{x:Type MenuItem}">
                <Setter Property="Command" Value="{Binding Command}" />
            </Style>
        </Menu.ItemContainerStyle>
        <Menu.ItemTemplate>
            <HierarchicalDataTemplate ItemsSource="{Binding Path=MenuItems}">
                <TextBlock Text="{Binding Header}"/>
            </HierarchicalDataTemplate>
        </Menu.ItemTemplate>
    </Menu>
    <ContentControl Content="{Binding CurrentPageViewModel}" >

    </ContentControl>
</DockPanel>

As you can see from the code, it has a binded menu (which does not change) and a ContentControl, which calls a UserControl depending on what button has been pressed on the menu. The ContentControl is binded and uses a MVVM model to load the UserControl.

The problem is that the UserControl is not using a MVVM schema (only the loading part uses the MVVM). They are directly operating in c# using a direct WPF model (.cs and .xaml), so the UserControl ViewModel does not bind anything in the Model UserControl.

I want to find a way to pass the login information to the called UserControl. In a way that every time it changes the ContentControl, the new UserControl will have acces to the login data.

Is there any way to create a global-like variable that can be posted by the login or the main window, and read by each of the UserControls?


Solution

  • It is not exactly what i wanted but i did the trick by using the project properties.

    I set it in the loggin and get it in the window i want.

        object  myProperty = App.Current.Properties["Test"];