How to attach a ViewModel to a UserControl? In the case of window, I always did this:

new MainWindow() { DataContext = new MainVm() }; 

If you do so for UserControl, the compiler swears. How to act in this situation?

PS For the overall picture I will explain what effect I am aiming at: there is a main window, and depending on user clicks, different, unrelated data should be displayed. Therefore, for each of these data, I want to create separate UserControl and Vm, and, if necessary, just replace one UserControl with another. If I have the wrong approach, correct me.

    1 answer 1

    The control should not set itself DataContext . DataContext must set the parent element. Do something like this:

     <Window ...> <Grid> <local:MyUserControl DataContext="{Binding CurrentUser}"/> <local:MyAnotherUserControl DataContext="{Binding Tracks}"/> <local:MyThirdUserControl DataContext="{Binding SelectedTags}"/> </Grid> </Window> 

    That is: the necessary VMs for parts that are represented as controls must be in MainVM as properties. (Thus, by the way, all VMs will be able to communicate through the central VM.)

    I hope you get the idea.


    By the way, the main window should not create a VM either. Usually done like this:

     <Application x:Class="Namespace.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <!-- убрал StartupUri --> </Application> 
     public partial class App : Application { MainVM mainVM = new MainVM(); protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); new MainWindow() { DataContext = mainVM }.Show(); } } 
    • The idea caught. Thank! - Lightness
    • @Lightness: Please! - VladD