我为商店ViewModels做了一个类
internal class Locator
{
public MainViewModel MainViewModel { get; } = new MainViewModel();
}并将其添加到应用程序资源中
<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>然后将其定位器绑定到主窗口
<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>它起作用了。
当我向页面添加绑定(DataContext)时。它抛出一个异常(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>如何将DataContext绑定到页面?
发布于 2020-11-17 02:31:01
在定位器实例的App.xaml声明中不需要x:Name,x:Key就足够了
发布于 2020-11-17 23:39:37
当您在视图模型中实例化Page本身时,最容易出现错误。
视图模型不应该创建Page对象。尝试返回Uri并绑定到Source属性:
<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>这应该是可行的:
public class MainViewModel
{
public Uri Page { get; } = new Uri("Page1.xaml", UriKind.RelativeOrAbsolute);
}https://stackoverflow.com/questions/64863599
复制相似问题