Reputation: 893
Just started using Xamarin - been using PRISM with WPF for 10 years. Can't get binding for button commands working. Binding Label to property works fine (Blah prop). I set the BindingContext in code (in the VM ctor) (because I split up Views and ViewModels in different projects).
When I click the button in app the command handler never fires. If I set the command on the button in code (uncomment last line of the VM ctor).
Anyone know why this is not working? am I missing something? Do I need to use the ViewModelLocator and bind it in XAML? thanks.
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);
}
}
VM (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();
}
Upvotes: 3
Views: 1816
Reputation: 7445
All you have to do (using the code as you shared) is to move the setting of the BindingContext to the end of your ViewModel constructor, like
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;
}
The problem with your piece of code is that at the start of the ViewModel constructor you set the binding, and just after that you create the command. In that point the binding to the command is broken. That is why you have to move the setting of the BindingContext to the end, so that the binding is set on the created Command...
Upvotes: 2