我正在使用最新的Template 10 VS扩展来创建一个UWP Windows 10移动应用程序。
我已经更新了模板,以使用IOC(Autofac),以便在app.xaml.cs
中覆盖的INavigable ResolveForPage(Page page, NavigationService)
方法中解析ViewModels。
我还更新了每个页面类以具有ViewModel属性,例如:
public sealed partial class LoginPage : Page
{
private LoginPageViewModel _viewModel;
public LoginPageViewModel ViewModel => _viewModel ?? (_viewModel = (LoginPageViewModel)DataContext);
public LoginPage()
{
InitializeComponent();
NavigationCacheMode = Windows.UI.Xaml.Navigation.NavigationCacheMode.Enabled;
}
}
迄今为止,这一直很好,因为我只在视图中使用了 x:Bind
,并且与视图模型的绑定起作用。自从我安装了Template 10验证包后,我已经更新了一些视图,以使用旧的 Binding
方法,例如:
<validate:ControlWrapper PropertyName="Password">
<TextBox x:Name="Password"
HorizontalAlignment="Left"
Margin="10,220,0,0"
TextWrapping="Wrap"
Text="{Binding ViewModel.LoginModel.Password, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
VerticalAlignment="Top"
Width="{StaticResource FieldWidth}"
Height="60"
PlaceholderText="Password"
FontSize="24"
InputScope="Password">
<Interactivity:Interaction.Behaviors>
<Core:EventTriggerBehavior>
<Behaviors:FocusAction />
</Core:EventTriggerBehavior>
</Interactivity:Interaction.Behaviors>
</TextBox>
</validate:ControlWrapper>
我遇到的问题是文本绑定
Text="{Binding ViewModel.LoginModel.Password, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
无法正常工作,并显示错误 Cannot resolve symbol ViewModel due to unknown DataContext
。由于我对UWP不熟悉,我认为我缺少一些必要的配置,以确保DataContext设置为正确的ViewModel。我尝试在
app.xaml.cs
构造函数中添加 DataContext = this
,但这并没有起作用。请问我缺少了哪个部分?