Home > database >  ContentControl with DataTemplate is not displaying anything (WPF MVVM)
ContentControl with DataTemplate is not displaying anything (WPF MVVM)

Time:11-07

In my MainView, there is a Frame containing a ContentControl supposed to show a View depending on a ViewModel set in MainViewModel.
However, nothing shows on my MainView. Any idea why?

MainView

<Grid>
    <Frame HorizontalAlignment="Center">
        <Frame.Content>
            <ContentControl Content="{Binding TestViewContext}">
                <ContentControl.Resources>
                    <DataTemplate DataType="{x:Type local:TestViewModel}">
                        <local:TestView />
                    </DataTemplate>
                </ContentControl.Resources>
            </ContentControl>
        </Frame.Content>
    </Frame>
</Grid>

MainViewModel

public class MainViewModel : BaseViewModel
{
    private TestViewModel _testViewContext;
    public TestViewModel TestViewContext
    {
        get { return _testViewContext; }
        set { _testViewContext = value; OnPropertyChanged(nameof(TestViewContext)); }
    }

    public MainViewModel()
    {
        TestViewContext = new TestViewModel();
    }
}

TestView
Just a red colored Page

TestViewModel

public class TestViewModel : ViewModelBase
{}

CodePudding user response:

Frame is a bit special. Normally, child controls inherit the DataContext of their parent. However, with a Frame, the children do not inherit the DataContext. As a result, your ContentControl has a DataContext of null.

To verify this, give your ContentControl a name like the following:

<ContentControl x:Name="MyContentControl" Content="{Binding TestViewContext}">

Then in the constructor of your MainView, check the DataContext as follows:

public MainView()
{
    // Other code

    // Set a breakpoint here and view the DataContext
    var dataContext = MyContentControl.DataContext;
}

For further reading, you could read the following post: page.DataContext not inherited from parent Frame?

Also, as a side note, Frame intended use was setting the Source property to an external file. As you may have noticed, in order to set child content in xaml, you need to specify <Frame.Content> unlike other controls.

  • Related