Connecting a window using a ViewModel

I have the following code

<Window.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="UI/ResourceDirectory.xaml"/>
        </ResourceDictionary.MergedDictionaries>
        <DataTemplate DataType="{x:Type vm:MainWindowViewModel}">
            <local:MainWindow></local:MainWindow>
        </DataTemplate>
    </ResourceDictionary>

</Window.Resources>

      

And it gives the following error

Cannot fit window to style

I found this answer.

I did all the necessary UI coding in the main window, but it is not possible to connect it to the corresponding ViewModel (placed in another project and I am using its link).

So my questions are: "Why can't I do this?", "How do I connect the window control using the ViewModel?", "Should I use UserControl instead?"

+3


source to share


2 answers


You are trying to put one window inside another and it is not possible. Connecting View and ViewModel is much simpler, but depends on your project structure. You can set it in the constructor Window

, for example:

public partial class MainWindow : Window    
{
    public MainWindow ()
    {
        this.DataContext = new MainWindowViewModel();
        InitializeComponent();
    }
}

      



The approach you're trying to do just doesn't work for Windows

and is only useful when you put the ViewModels in XAML yourself.

0


source


To connect the viewmodel to the view, you must do the following in the xaml code.

<Window.DataContext>
   <viewModel:MainWindowViewModel/>
</Window.DataContext>

      

ViewModel is a namespace.



xmlns:viewModel="clr-namespace:TestProject.ViewModel"

      

You don't have to set the viewmodel in the codebehind of the view!

0


source







All Articles