【问题标题】:Xaml Binding cannot see ViewModel in Template 10 appXaml 绑定在模板 10 应用程序中看不到 ViewModel
【发布时间】:2017-04-24 22:58:37
【问题描述】:

我正在使用最新的 Template 10 VS 扩展来创建 UWP Windows 10 移动应用。 我已经更新了模板以使用 IOC (Autofac),因此 ViewModels 在 app.xaml.cs 覆盖 INavigable ResolveForPage(Page page, NavigationService) 方法中得到解决。 我还更新了 Page 类,每个类都有一个 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,并且绑定到视图模型有效。由于我安装了模板 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,但这不起作用。

谁能告诉我我错过了谜题的哪一部分?

【问题讨论】:

    标签: xaml uwp datacontext template10


    【解决方案1】:

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

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

    我认为这应该是一个好的开始,可以引导您朝着正确的方向前进;)

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

    【讨论】:

    • 这正是我需要让它工作的提示。按照您的建议设置绑定有效。我也会对它做一些更彻底的阅读。现在找出为什么在代码中设置的验证错误没有显示在视图中。感谢您的帮助。
    • @Steve 很高兴它有帮助。问题/问题通常是阅读、学习和深入了解发生的事情以及为什么我没有工作的良好开端。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-14
    • 2012-08-15
    • 1970-01-01
    • 1970-01-01
    • 2016-04-28
    相关资源
    最近更新 更多