I've built WPF app using MVVM design with some simple navigation. I added two Views(User Controls) and dummy ViewModels (empty classess) to the project to switch them through this navigation. Here is my folder structure: Folder Structure
So when I click i.e. on the first button in navi instead of the view of user control, I got the name of the ViewModel like this: App screen (View.ViewModels.NameoftheViewModel)
Here is how I implemented this:
Window.Resources with DataTemplate
Navi buttons for switching user controls
MainWindow.xaml.cs :
public MainWindow()
{
InitializeComponent();
this.DataContext = new NavigationViewModel();
}
NavigationViewModel used for switching :
class NavigationViewModel : INotifyPropertyChanged
{
public ICommand CurrencyCommand { get; set; }
public ICommand GoldCommand { get; set; }
private object selectedViewModel;
public object SelectedViewModel
{
get { return selectedViewModel; }
set { selectedViewModel = value; OnPropertyChanged("SelectedViewModel"); }
}
public NavigationViewModel()
{
CurrencyCommand = new BaseCommand(OpenCurrency);
GoldCommand = new BaseCommand(OpenGold);
}
public void OpenCurrency(object obj)
{
SelectedViewModel = new CurrencyViewModel();
}
public void OpenGold(object obj)
{
SelectedViewModel = new GoldViewModel();
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propName));
}
}
}
BaseCommand class simply implements ICommand interface.
XAML for showing user controls :
<ContentControl Margin="45, 50, 0, 0" Content="{Binding SelectedViewModel}"/>
Does anyone knows why is this happening? I did this from the tutorial: Tutorial link and it works all fine for this tutorial case but in my project it does not.
from linked tutorial:
Create a DataTemplate of type EmployeeViewModel and it should contain EmployeeView UserControl inside it. Important thing is you should specify any key to the DataTemplates, since these DataTemplates are going to get queried by their DataType.
you should not specify x:Key
for DataTemplates for your view models. DataTemplates can be picked by DataType only if there is no x:Key
<DataTemplate DataType="{x:Type vm:CurrencyViewModel}">
<vs:CurrencyControl/>
</DataTemplate>