【问题标题】:Add ViewModel to Mobile View将 ViewModel 添加到移动视图
【发布时间】:2016-07-06 02:54:23
【问题描述】:

我正在为移动设备制作一组单独的视图,而不是为手机使用额外的自适应 UI 状态。我可以通过在我的Views 文件夹中添加一个名为DeviceFamily-Mobile 的子文件夹并添加一个与我覆盖的名称相同的新View 来实现这一点。

我有以下View 可以在移动设备/模拟器上工作并显示“MOBILE”。

<Page x:Class="MyApp.PayeesPage"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:behaviors="using:Template10.Behaviors"
      xmlns:controls="using:Template10.Controls"
      xmlns:core="using:Microsoft.Xaml.Interactions.Core"
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
      xmlns:interactivity="using:Microsoft.Xaml.Interactivity"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
      xmlns:models="using:MyApp.Models"
      xmlns:viewModels="using:MyApp.ViewModels"
      xmlns:views="using:MyApp.Views"
      mc:Ignorable="d">

    <RelativePanel Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <TextBlock x:Name="MobileTextBlock"
                   Foreground="{ThemeResource ForegroundColorBrush}"
                   Text="MOBILE" />
    </RelativePanel>
</Page>

但是,如果我尝试设置 DataContext 以允许我实际显示一些有用的内容,例如:

<Page.DataContext>
    <viewModels:PayeesPageViewModel x:Name="ViewModel" />
</Page.DataContext>

然后在导航到PayeesPage 时出现错误:

无法将“Windows.UI.Xaml.Controls.TextBlock”类型的对象转换为“MyApp.ViewModels.PayeesPageViewModel”类型。

这与我在原始PayeesPage 上设置DataContext 的方式相同,并且效果很好。有没有其他方法可以在这些备用 Views 上设置 DataContext,或者我错过了什么?

【问题讨论】:

    标签: xaml uwp uwp-xaml


    【解决方案1】:

    原来手机View需要和原来的Page有相同的x:Class。当我尝试将 ReSharper 称为 MyApp.Views.PayeesPage 时,它在抱怨,因为它已经存在,所以我将其更改为 MyApp.PayeesPage。但是,当我将其切换回来以便两者都使用相同的 x:Class 时,一切都开始按预期工作。

    不幸的是,我从 ReSharper 收到了一堆红色波浪线,但一切正常。以防万一将来有人遇到这个问题:

    查看次数/PayeesPage.xaml:

    <Page x:Class="MyApp.Views.PayeesPage"
     ...>
    

    Views/DeviceFamily-Mobile/PayeesPage.xaml:

    <Page x:Class="MyApp.Views.PayeesPage"
     ...>
    

    【讨论】:

    • 感谢分享您的解决方案,有很多文章谈论 DeviceFamily-Type 文件夹,例如igrali.com/2015/08/02/…
    • 这是一篇不错的文章 - 我从中获得了很多信息。我的问题是,我发现的所有信息都没有指出视图需要共享相同的x:Class,因此在这种情况下,来自 ReSharper 的红色曲线有点误导。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-07
    相关资源
    最近更新 更多