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?