0

I made a class for store ViewModels

internal class Locator
{
    public MainViewModel MainViewModel { get; } = new MainViewModel();
}

And added it to application resources

<Application x:Class="Marathon.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:Marathon"
             StartupUri="MainWindow.xaml">
    <Application.Resources>
         <local:Locator x:Key="Locator" x:Name="Locator"/>
    </Application.Resources>
</Application>

Then bound it Locator to the Main Window

<Window x:Class="App.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d"
        DataContext="{Binding Source={StaticResource Locator}, Path=MainViewModel}"
        Title="MainWindow" MinHeight="350" MinWidth="525">
    <Grid>
        <Frame Content="{Binding Page}"></Frame>
    </Grid>
</Window>

It works.

When I add a binding (DataContext) to a Page. It throws an exception (System.Windows.Markup.XamlParseException, Cannot find resource named 'Locator'.).

<Page x:Class="App.Pages.StartPage"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
      mc:Ignorable="d"
      DataContext="{Binding Source={StaticResource Locator}, Path=MainViewModel}"
      Title="StartPage">
    <Grid>
        
    </Grid>
</Page>

How to bind DataContext to a page?

Wootiae
  • 728
  • 1
  • 7
  • 17

2 Answers2

0

You don't need x:Name in your App.xaml declaration of the locator instance, x:Key is sufficient

Peregrine
  • 4,287
  • 3
  • 17
  • 34
0

The error most occurs if and when you instantiate the Page itself in the view model.

A view model shouldn't create Page objects. Try to return a Uri instead and bind to the Source property instead:

<Window x:Class="App.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d"
        DataContext="{Binding Source={StaticResource Locator}, Path=MainViewModel}"
        Title="MainWindow" MinHeight="350" MinWidth="525">
    <Grid>
        <Frame Source="{Binding Page}" />
    </Grid>
</Window>

This should work:

public class MainViewModel
{
    public Uri Page { get; } = new Uri("Page1.xaml", UriKind.RelativeOrAbsolute);
}
mm8
  • 163,881
  • 10
  • 57
  • 88