如何解决Stacklayout BindableLayout 中的 Xamarin Forms Switch 使用 MVVM (Prism.Forms) 获取切换事件
我有以下列表:
<StackLayout BindableLayout.ItemsSource="{Binding NotificationList}" Margin="0,10,10" >
<BindableLayout.ItemTemplate>
<DataTemplate> <StackLayout Style="{StaticResource StacklayoutAStyle}">
<Label Text="{Binding notificationLabel}" VerticalOptions="Center" VerticalTextAlignment="Center"/>
<Switch IsToggled="{Binding isNotificationToggled,Mode=TwoWay}" VerticalOptions="Center" HorizontalOptions="End" />
</StackLayout>
</DataTemplate>
</BindableLayout.ItemTemplate>
</StackLayout>
我想在切换列表中的相应开关时获取 notificationLabel 文本。我的 viewmodel 看起来像这样:
private ObservableCollection<NotificationModel> _notificationList = new ObservableCollection<NotificationModel>
{
new NotificationModel { notificationLabel = "Notification1",isNotificationToggled = true },new NotificationModel { notificationLabel = "Notification2",isNotificationToggled = false },new NotificationModel { notificationLabel = "Notification3",new NotificationModel { notificationLabel = "Notification4",};
public ObservableCollection<NotificationModel> NotificationList
{
get { return _notificationList; }
set { SetProperty(ref _notificationList,value); }
}
例如,当我切换通知 3 时,它会切换为开启 (true),但如何使用“通知 3”捕获该事件?
解决方法
可以使用Switch.Toggled
监听toggled事件,然后获取BindingContext(NotificationModel
),然后根据NotificationModel.notificationLabel
判断哪个Switch是开启的。
<StackLayout BindableLayout.ItemsSource="{Binding NotificationList}" Margin="0,10,10" >
<BindableLayout.ItemTemplate>
<DataTemplate>
<StackLayout Style="{StaticResource StacklayoutAStyle}">
<Label Text="{Binding notificationLabel}" VerticalOptions="Center" VerticalTextAlignment="Center"/>
<Switch IsToggled="{Binding isNotificationToggled,Mode=TwoWay}" VerticalOptions="Center" HorizontalOptions="End" Toggled="Switch_Toggled" />
</StackLayout>
</DataTemplate>
</BindableLayout.ItemTemplate>
</StackLayout>
在您的 page.xaml.cs 中:
private void Switch_Toggled(object sender,ToggledEventArgs e)
{
Switch sw = sender as Switch;
NotificationModel notificationModel = (NotificationModel)sw.BindingContext;
if (e.Value)
{
switch (notificationModel.notificationLabel)
{
case "Notification1":
//do something
break;
case "Notification2":
//do something
break;
case "Notification3":
//do something
break;
case "Notification4":
//do something
break;
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。