首页 > 解决方案 > 无法绑定 ViewModelLocator

问题描述

我为商店 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 绑定到页面?

标签: c#wpfxamldata-binding

解决方案


当您Page在视图模型中实例化自身时,最容易发生错误。

视图模型不应该创建Page对象。尝试返回 aUri并改为绑定到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);
}

推荐阅读