C# Xamarin MVVM按钮绑定到命令无效
刚开始使用Xamarin-在WPF中使用PRISM已有10年了。无法使按钮命令的绑定正常工作。将标签绑定到属性可以正常工作(废话道具)。我在代码中设置了BindingContext(在VM ctor中)(因为我在不同的项目中分割了视图和视图模型) 当我单击应用程序中的按钮时,命令处理程序从不触发。如果我在代码中的按钮上设置了该命令(取消对VM ctor最后一行的注释) 有人知道为什么这不起作用吗?我错过什么了吗?我是否需要使用ViewModelLocator并将其绑定到XAML中?谢谢 XAML(MainPage.XAML): VM(MainPageViewModel.cs): 简短的回答 您所要做的(使用共享的代码)就是将BindingContext的设置移动到ViewModel构造函数的末尾,如C# Xamarin MVVM按钮绑定到命令无效,c#,xaml,xamarin.forms,prism,C#,Xaml,Xamarin.forms,Prism,刚开始使用Xamarin-在WPF中使用PRISM已有10年了。无法使按钮命令的绑定正常工作。将标签绑定到属性可以正常工作(废话道具)。我在代码中设置了BindingContext(在VM ctor中)(因为我在不同的项目中分割了视图和视图模型) 当我单击应用程序中的按钮时,命令处理程序从不触发。如果我在代码中的按钮上设置了该命令(取消对VM ctor最后一行的注释) 有人知道为什么这不起作用吗?我错过什么了吗?我是否需要使用ViewModelLocator并将其绑定到XAML中?谢谢 XAML
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的设置移动到末尾,以便在创建的命令上设置绑定,…,而它不是答案,Prism是多余的,因为Xamarin有一个非常好的MVVM,它是开箱即用的,不像WPF。谢谢,我一开始用Prism试用过它,但也不起作用……谢谢-嗯,在WPF/Prism桌面上工作过,我们把它放在基类构造函数中(我简化了代码,不包括基类)。好的,非常感谢!
public partial class MainPage
{
public MainPage()
{
InitializeComponent();
}
public Button RotateButton => rotateButton;
public async void RotateLabel()
{
await label.RelRotateTo(360, 1000);
}
}
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();
}
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;
}