我正在关注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!";
现在,在设计时,文本在设计器中显得很好,但是当我运行应用程序时,我只得到一个空白页面,我无法找出原因?
任何建议都会有所帮助。
答案 0 :(得分:0)
我认为,您只声明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">