Search code examples
c#.netxamlmauimaui-community-toolkit

Relay Command Wont Execute


I've reviewed a few other questions on this subject and haven't found a solution.

Databinding is working, I tested with different labels and entry fields to make sure. I am not getting a data binding failure. I am using the CommunityToolkit.Mvvm. That said, here is the code.

XAML

<Button Grid.Row="6" Grid.Column="1" Grid.ColumnSpan="2"
       Text="Calculate"
       Command="{Binding CalculateValue}"
       FontSize="Small"
       HorizontalOptions="Center" />



 C#   
[RelayCommand]

private void CalculateValue()
{

    TotalValue = 100;
}

I know its binding now because the original snippet gave a binding error because of an error (was public instead of private), but now that that is corrected its simply not executing. I have TotalValue bound to another label within the View and it doesn't update. I've also attempted to use a Breakpoint at the fuction, and no luck there.

One thing that stands out to me (since I looked at examples from MS) is my class is labeled as partial and theirs is not. I get an error if I don't define it as partial (which the documentation says to do) so that makes sense, but the sample they have on Github does not.

Appreciate all the help.


Solution

  • Found the issue. In the View cs file, I was setting the binding source before

    InitializeComponents();
    

    I did this because I got the binding error on the Command if I did it after. I set the BindingContext after Initialize, which brought back the binding error, but then I realized I needed to add 'Command' at the end of the name. Corrected code should look like this.

    <Button Grid.Row="6" Grid.Column="1" Grid.ColumnSpan="2"
           Text="Calculate"
           Command="{Binding CalculateValueCommand}"
           FontSize="Small"
           HorizontalOptions="Center" />