【发布时间】: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