Answer the question
In order to leave comments, you need to log in
How to properly specify DataContext in MVVM UserControl?
There is such code in MainWindow.xaml:
<Window.Resources>
<DataTemplate
DataType="{x:Type vm:MainMenuVM}">
<v:MainMenu />
</DataTemplate>
<DataTemplate
DataType="{x:Type vm:DataBaseEditorVM}">
<v:DataBaseEditor />
</DataTemplate>
</Window.Resources>
<ContentPresenter Content="{Binding CurrentContentVM}"/>
public class RootVM : ObservableObject
{
private readonly Dictionary<string, BaseVM> mViewModels = new Dictionary<string, BaseVM>();
private BaseVM mCurrentContentVM;
public BaseVM CurrentContentVM
{
get => mCurrentContentVM;
set
{
mCurrentContentVM = value;
OnPropertyChanged("CurrentVM");
}
}
public RootVM()
{
mViewModels.Add("MainMenu", new MainMenuVM(this));
mViewModels.Add("DataBaseEditor", new DataBaseEditorVM(this));
SetVM("MainMenu");
}
public void SetVM(string vmName)
{
if (mViewModels.ContainsKey(vmName))
{
CurrentContentVM = mViewModels[vmName];
}
}
}
new MainWindow { DataContext = RootVM }.Show();
public Command OpenDataBaseEditorView
{
get => mOpenDataBaseEditorView ??
(mOpenDataBaseEditorView = new Command((o) =>
{
mParentVM.SetVM("DataBaseEditor");
}));
private set { }
}
<Button Click="{Binding OpenDataBaseEditorView}">Open</Button>
Answer the question
In order to leave comments, you need to log in
The problem is not with the assignment of the DataContext to the UserControl . To bind a command to a button, use the Command property rather than the Click property :
<Button Command="{Binding OpenDataBaseEditorView}">Open</Button>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question