【问题标题】:Can't bind ViewModelLocator无法绑定 ViewModelLocator
【发布时间】:2020-11-16 18:26:18
【问题描述】:

我为商店 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# wpf xaml data-binding


【解决方案1】:

在定位器实例的App.xaml 声明中不需要x:Name,x:Key 就足够了

【讨论】:

  • 感谢这个问题,但它并没有解决问题。
  • 会不会是因为我不使用DI,只是通过构造函数创建ViewModel?
【解决方案2】:

当您在视图模型中实例化 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);
}

【讨论】:

    猜你喜欢
    • 2014-07-31
    • 2012-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多