【问题标题】:Xamarin unable to bind ICommand in code/view modelXamarin 无法在代码/视图模型中绑定 ICommand
【发布时间】:2018-04-10 21:39:50
【问题描述】:

我正在使用 VS 2017 的 MVVM 方法开发一个简单的 Xamarin.Forms 应用程序。在 UWP 中一切正常,但我的 Android 项目根本不执行获取/设置 ICommand 属性的代码行。我可以在设置属性值的行以及之前的行和之后的行上设置断点。我在前后两行都打断了,但不在设置属性的行上打断。

这是我的视图模型代码:

public LoginPageViewModel(INavigation navigation) : base() 
{
        Navigation = navigation;
        LoginButtonClicked = new Command(Login, () => true);
        PasswordHintButtonClicked = new Command(PasswordHint, () => true);
}

还有我的 XAML.cs:

btnLogin.SetBinding(Button.CommandProperty,  nameof(vm.LoginButtonClicked), BindingMode.OneWay);
btnPasswordHint.SetBinding(Button.CommandProperty, nameof(vm.PasswordHintButtonClicked), BindingMode.OneWay);

正如我所说,我可以设置 Navigation 属性,但不能设置命令属性。如果我将 Navigation = navigation 移动到构造函数的最后一行,我仍然会中断它。

我也试过了:

private ICommand _loginButtonClicked;
public ICommand LoginButtonClicked
{
    get { return _loginButtonClicked ?? (_loginButtonClicked = new 
    Command(Login, () => true)); }
}

这应该很简单。也许我在配置 Android 模拟器时出错了?几天来我一直在反对这个问题,如果有人在我之前看到过这样的事情,我会很感激朝着正确的方向轻推。

【问题讨论】:

    标签: android xamarin.forms


    【解决方案1】:

    看来您需要在SetBinding 方法之前设置BindingContext。 例如,如果代码如下所示:

            public MainPage()
            {
                InitializeComponent();
                LoginPageViewModel vm = new LoginPageViewModel();
                BindingContext = vm;
                btnLogin.SetBinding(Button.CommandProperty, nameof(vm.LoginButtonClicked), BindingMode.OneWay);
                btnPasswordHint.SetBinding(Button.CommandProperty, nameof(vm.PasswordHintButtonClicked), BindingMode.OneWay);                
            }
    

    然后它可以在设置属性的行上中断并调用方法。

    您可以参考此link 了解更多信息。

    【讨论】:

      【解决方案2】:

      如果有人碰巧遇到这个问题,在我的情况下,它是由于缺少Preserve 属性引起的。我已将属性添加到所有外部程序集,但我的视图模型也需要它。出于某种原因,即使在 .xaml.cs 页面中引用了链接器,它也没有拉入整个类。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-06-03
        • 1970-01-01
        • 2013-10-16
        • 2020-06-20
        • 2020-01-29
        • 1970-01-01
        • 2011-05-26
        • 1970-01-01
        相关资源
        最近更新 更多