【问题标题】:MVVM Light UWP view only showing at design timeMVVM Light UWP 视图仅在设计时显示
【发布时间】:2017-01-27 09:13:52
【问题描述】:

我正在学习关于 MVVM Light 和 UWP 的初学者教程。我有一个 ViewModel,它只有一个字符串字段,在主视图中绑定到 TextBlock,如下所示:

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <TextBlock Name="Title"  HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="24" Text="{Binding Title}" />
</Grid>

ViewModelLocator 在 App.xaml 中是这样定义的:

<Application.Resources>
    <vm:ViewModelLocator xmlns:vm="using:MvvmLight.UWP.ViewModels" x:Key="Locator" />
</Application.Resources>

ViewModelLocator 类如下所示:

public ViewModelLocator()
{   
    ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
    SimpleIoc.Default.Register<StartPageViewModel>();
}

public StartPageViewModel StartPageInstance
{
    get { return ServiceLocator.Current.GetInstance<StartPageViewModel>(); }
}

在 ViewModel 中,我在构造函数中有这个:

Title = "Hello world!";

现在,在设计时,文本在设计器中显示正常,但是当我运行应用程序时,我只得到一个空白页,我不知道为什么?

【问题讨论】:

    标签: c# uwp mvvm-light


    【解决方案1】:

    我认为,你只声明Design Time DataContext,你也应该在你的视图的属性中声明Runtime DataContext。为此,添加以下内容:

    DataContext="{Binding Source={StaticResource Locator}, Path=StartPageInstance}"
    

    在此之后,您将拥有类似的东西:

    <Page
        x:Class="App1.MainPage"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="using:App1"
        xmlns:design="using:App1.Design"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        DataContext="{Binding Source={StaticResource Locator}, Path=StartPageInstance}"
        d:DataContext="{d:DesignInstance Type=design:DesignStartPageInstance, IsDesignTimeCreatable=True}"
        mc:Ignorable="d">
    

    【讨论】:

    • 在 StartPage.xaml 中声明的唯一 DataContext 是这个:DataContext="{Binding StartPageInstance, Source={StaticResource Locator}}"
    • 正如我在问题中所说,我看到了设计时文本,但在运行时看不到它。
    • Title 属性的 setter 通知了吗?
    • 你能添加你的 xaml 代码和 ViewModel 代码吗?
    猜你喜欢
    • 1970-01-01
    • 2017-11-17
    • 1970-01-01
    • 2021-04-19
    • 1970-01-01
    • 2014-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多