【问题标题】:Xamarin MVVM Button Binding To Command Not WorkingXamarin MVVM 按钮绑定到命令不起作用
【发布时间】:2020-03-06 14:50:19
【问题描述】:

刚开始使用 Xamarin - 使用 PRISM 和 WPF 已有 10 年了。无法绑定按钮命令的工作。将标签绑定到属性工作正常(Blah 道具)。我在代码中(在 VM ctor 中)设置了 BindingContext(因为我在不同的项目中拆分了 Views 和 ViewModels)。

当我单击应用程序中的按钮时,命令处理程序永远不会触发。如果我在代码中的按钮上设置命令(取消注释 VM ctor 的最后一行)。

有人知道为什么这不起作用吗?我错过了什么吗?我是否需要使用 ViewModelLocator 并将其绑定到 XAML 中?谢谢。

XAML (MainPage.xaml):

        <Label Text="{Binding Blah}" />

        <Button
        x:Name="rotateButton"
        Command="{Binding RotateCommand}"
        HorizontalOptions="Center"
        Text="Click to Rotate Text!"
        VerticalOptions="CenterAndExpand" />

XAML (MainPage.xaml.cs):

    public partial class MainPage
{
    public MainPage()
    {
        InitializeComponent();
    }

    public Button RotateButton => rotateButton;

    public async void RotateLabel()
    {
        await label.RelRotateTo(360, 1000);
    }
}

虚拟机(MainPageViewModel.cs):

    private string _blah;
    public MainPageViewModel(MainPage mainPage)
    {
        mainPage.BindingContext = this;
        RotateCommand = new Command(HandleRotateCommand,
            () => true);
        //if i uncomment this, the button fires.  not ideal obviously.
        //mainPage.RotateButton.Command = RotateCommand;
    }
    public ICommand RotateCommand { get; }

    public string Blah
    {
        get => _blah;
        set
        {
            _blah = value;
            OnPropertyChanged();
        }
    }

    private void HandleRotateCommand()
    {
        Debug.WriteLine("HandleRotateCommand");
        View.RotateLabel();
    }

【问题讨论】:

  • 虽然这不是答案,但 Prism 是多余的,因为 Xamarin 有一个非常好的开箱即用的 MVVM,不像 WPF。
  • 感谢我一开始在没有 Prism 的情况下尝试过,但也没有用...

标签: c# xaml xamarin.forms prism


【解决方案1】:

简短的回答

您所要做的(使用您共享的代码)就是将 BindingContext 的设置移动到 ViewModel 构造函数的末尾,例如

public MainPageViewModel(MainPage mainPage)
{

    RotateCommand = new Command(HandleRotateCommand,
        () => true);
    //if i uncomment this, the button fires.  not ideal obviously.
    //mainPage.RotateButton.Command = RotateCommand;

    mainPage.BindingContext = this;
}

说明

您的代码的问题在于,在 ViewModel 构造函数的开头设置了绑定,然后创建了命令。在那一点上,与命令的绑定被破坏了。这就是为什么您必须将 BindingContext 的设置移到最后,以便在创建的 Command...

上设置绑定

【讨论】:

  • 谢谢 - 嗯,在 WPF / Prism Desktop 上工作,我们把它放在一个基类构造函数中(我通过不包括基类来简化代码)。好的,非常感谢!
猜你喜欢
  • 1970-01-01
  • 2019-05-20
  • 1970-01-01
  • 2019-05-11
  • 2021-06-27
  • 2018-07-31
  • 2015-06-07
  • 2015-12-09
  • 2015-06-21
相关资源
最近更新 更多