Xaml Binding cannot see ViewModel in Template 10 app

时间:2016-12-09 12:46:05

标签: xaml uwp datacontext template10

I'm using the latest Template 10 VS extension to create a UWP Windows 10 mobile app. I've updated the template to use IOC (Autofac) so the ViewModels get resolved in the app.xaml.cs overridden INavigable ResolveForPage(Page page, NavigationService) method. I've also updated the Page classes to each have a ViewModel property such as:

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;
    }
}

This has been fine until now as I've only used x:Bind in views and the binding to the viewmodel works. Since I installed the Template 10 validation package I've updated some views to use the older Binding method such as

<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>

This issue I have is that the text binding, Text="{Binding ViewModel.LoginModel.Password, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" doesn't work with the error Cannot resolve symbol ViewModel due to unknown DataContext.

As I'm new to UWP I think I'm missing some required configuration to ensure the DataContext is set to the correct ViewModel. I did try adding DataContext = this in the app.xaml.cs constructor but this didn't work.

Can anyone tell me which part of the puzzle I am missing?

1 个答案:

答案 0 :(得分:3)

在此处查看新x:Bind和旧绑定difference-between-binding-and-xbind之间的区别。根据错误消息,旧绑定正在页面的DataContext上查找名为“ViewModel”的属性。但DataContext的类型为“LoginPageViewModel”,属性为“LoginModel”?所以,如果我是对的,你需要将文本绑定更改为

Text="{Binding LoginModel.Password, Mode=...

我认为这应该是指导你朝着正确方向前进的良好开端;)

也有助于学习和解读新旧绑定之间的区别:data-binding-in-depth