Can anyone point out why my Command is not triggering? This is my custom control
public partial class RateControl : Grid
{
public static readonly BindableProperty RateProperty = BindableProperty.Create(nameof(Rating), typeof(int), typeof(RateControl), 1, propertyChanged: OnRatePropertyChanged);
private static void OnRatePropertyChanged(BindableObject bindable, object oldValue, object newValue)
{
if(bindable is RateControl && bindable != null && newValue is int)
{
(bindable as RateControl).OnRateClicked((int)newValue);
}
}
public int Rating
{
set => SetValue(RateProperty, value);
get => (int)GetValue(RateProperty);
}
public ICommand OnRateSelectedCommand { get; set; }
public RateControl()
{
InitializeComponent();
OnRateSelectedCommand = new Command<int>(OnRateClicked);
}
private void OnRateClicked(int rating)
{
Rating = rating;
ChangeStar(Rating);
}
private void ChangeStar(int starcount)
{
for (int i = 1; i <= starcount; i )
{
(FindByName($"star{i}") as Label).Text = RsrIcon.StarFull;
}
for (int i = starcount 1; i <= 5; i )
{
(FindByName($"star{i}") as Label).Text = RsrIcon.StarEmpty;
}
}
}
And this is my Xaml
<Grid xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="Mobile.Controls.RateControl"
xmlns:common="clr-namespace:Mobile.Common"
xmlns:control="clr-namespace:Mobile.Controls"
RowDefinitions="Auto"
x:Name="component"
ColumnDefinitions="30,30,30,30,30"
ColumnSpacing="10">
<control:TappableLabel FontSize="Large"
x:Name="star1"
TappedCommand="{x:Binding OnRateSelectedCommand, Source={x:Reference component}}"
TappedCommandParameter="1"
Text="{Static common:RsrIcon.StarEmpty}"
TextColor="{StaticResource RsrYellow}"
VerticalOptions="Center"/>
.....
So the TappableLabel is just a custom TappedGesture, The thing is upon clicking the RateControl either be StarFull or StarEmpty. The initialization of the command is working, but upon clicking nothing is happening.
CodePudding user response:
I've never seen {x:Binding ...
used with Xamarin Forms.
Change it to {Binding ...
:
... TappedCommand="{Binding OnRateSelectedCommand, Source={x:Reference component}}"
Optionally, add as last line in constructor:
BindingContext = this;
Then you can do binding simply with {Binding OnRateSelectedCommand}
:
... TappedCommand="{Binding OnRateSelectedCommand}"
CodePudding user response:
The generic type of Command should be string
not int
.
Modify your code as below
//xaml
TappedCommand="{Binding OnRateSelectedCommand}"
public RateControl()
{
InitializeComponent();
OnRateSelectedCommand = new Command<string>(OnRateClicked);
BindingContext = this;
}
private void OnRateClicked(string rating)
{
}