I have been trying to follow the example for EventToCommandBehavior located at:
The example shows a selectedItem event being fired for an item in a list view. My hope is to fire a Switch event for any item in my list view.
I did make sure to change the EventName from "ItemsSelected" To "Toggled" (the event for the switch) but the event isn't hit at all. What could I be doing wrong?
FWIW, I'm trying to follow the MVVM pattern and minimize "code behind"
GaragePage.xaml
<ContentPage.Resources>
<ResourceDictionary>
<converters:ToggledItemEventArgsConverter x:Key="ToggledConverter" />
</ResourceDictionary>
</ContentPage.Resources>
<ListView x:Name="listView" VerticalOptions="StartAndExpand" HasUnevenRows="true" ItemsSource="{Binding Previews}" HeightRequest="800" SeparatorVisibility="None"
behaviors:ListViewBehavior.NoBackgroundSelection="True">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<cardView:CardView Margin="40,15,40,15" HeightRequest="200" CardViewOutlineColor="{StaticResource Primary}" Padding="5" CardViewOutlineColorThickness="1" CardViewHasShadow="True">
<cardView:CardView.CardViewContent>
<StackLayout Orientation="Vertical" BackgroundColor="White" >
<StackLayout VerticalOptions="CenterAndExpand" >
<StackLayout Grid.Row="0" Grid.Column="0" >
<StackLayout HorizontalOptions="Center">
<Label Text="Enable Mobile Alert" FontSize="Small" TextColor="{StaticResource LightTextColor}"/>
<Switch IsToggled="{Binding PushNotification}" HorizontalOptions="Center">
<Switch.Behaviors>
<behaviors:EventToCommandBehavior EventName="Toggled" Command="{Binding ToggleAlertCommand}" Converter="{StaticResource ToggledConverter}" />
</Switch.Behaviors>
</Switch>
</StackLayout>
</StackLayout>
</StackLayout>
</StackLayout>
</cardView:CardView.CardViewContent>
</cardView:CardView>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
GaragePageViewModel.cs
public ICommand ToggleAlertCommand { get; private set; }
public GaragePageViewModel()
{
ToggleAlertCommand = new Command<Vehicle>(ToggleMobileAlert);
}
private async Task ToggleMobileAlert(GarageVehicle vehicle)
{
//do work
}
ToggledItemEventArgsConverter.cs
public class ToggledItemEventArgsConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var eventArgs = value as ToggledEventArgs;
return eventArgs.Value;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
GaragePage.xaml.cs
public GaragePage()
{
InitializeComponent();
BindingContext = App.Container.Resolve<GaragePageViewModel>();
}