c# - 无法绑定 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 绑定到页面?
解决方案
当您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);
}
推荐阅读
- java - 在 docker 中运行的 Spring Boot SOAP 服务找不到 ExtensibilityElement 类
- reactjs - 从 S3/Cloudfront 上的 React SPA 移出,但用户的浏览器仍然显示旧的缓存 SPA
- laravel - 带有变量的 WhereRaw Laravel
- webpack - 遇到我不明白的 babel 构建错误
- r - 打印数据框行时,R Markdown 消除了“##”
- python - Chromedriver找到一个xpath就可以了,但在无头时却不行
- vba - 如何在段落中搜索多个字符串(列表中的任何一个字符串)(使用输入和输出图像更新)
- regex - 负前瞻行为
- wpf - WPF 用阻塞我的 UI 线程的大表填充 DataGrid
- dart - 暂停颤振倒数计时器