0

I have been stuck with this problem for a few hours now. I followed this answer which seemed to be the most relevant (no frameworks) WPF MVVM navigate views, but I am missing something and it doesn't work. It only displays the .toString method on the screen instead of the actual data template.

What I have is a MainWindow.xaml, View1.xaml and View2.xaml and associated ViewModels. Both Views have buttons that can go to the other view. Why does ContentControl only displays .toString()?

MainWindow.xaml

<Window.Resources>
    <DataTemplate x:Key="View1Template" DataType="{x:Type viewmodels:View1Model}">
        <views:View1 />
    </DataTemplate>
    <DataTemplate x:Key="View2Template" DataType="{x:Type viewmodels:View2Model}">
        <views:View2 />
    </DataTemplate>
</Window.Resources>

<Grid>
    <ContentControl Content="{Binding CurrentView}" />
</Grid>

MainWindowViewModel.cs

public class MainWindowViewModel : ViewModelBase
{

    private ViewModelBase currentView;

    public ViewModelBase CurrentView
    {
        get
        {
            return currentView;
        }
        set
        {
            if (currentView != value)
            {
                currentView = value;
                OnPropertyChanged("CurrentView");
            }
        }
    }

    public MainWindowViewModel ()
    {
        CurrentView = new View1Model();
    }

}

How should I make this work? Moreover, where should the commands for swapping the views be? In this MainWindowViewModel.cs?

DataContext is set in the code-behind.

karolyzz
  • 480
  • 4
  • 28
  • 2
    remove `x:Key="..."` from DataTemplates. if they are not named, they are picked up based on DataType. Linked example doesn't have `x:Key`. also linked example says about ICommand in a *view model* – ASh Jul 10 '18 at 13:06
  • 1
    This may help you: https://stackoverflow.com/a/6114865/885920 – S2S2 Jul 10 '18 at 13:08
  • Can you please write this part of x:key as an answer? It solved the main problem – karolyzz Jul 10 '18 at 13:09

1 Answers1

2

to make example work remove x:Key="..." from DataTemplates.


ContentControl binds to CurrentView. CurrentView is a view model instance and doesn't have visual representation (doesn't derive from framework Visual class).

There is no ContentTemplate, so ContentControl tries to find a default DataTemplate for View1Model (or View2Model) type. but both DataTemplates which are declared in Resources, are not default, they are named with x:Key. So ContentControl finds nothing and falls back to guaranted method: display string representation of Content, because every .NET object has ToString() method.

ASh
  • 34,632
  • 9
  • 60
  • 82