问题描述
我有一个带有切换开关的 Listview
。我只想使用切换开关在 Listview
中选择一项。当我选择第二个切换时,第一个切换必须再次停用。例如在图片中;当我选择 Rekorida 然后我选择 Merchandizing
时,Rekorida
必须转回禁用。每次只能激活一个选项。在 Xamarin 中可以做到吗?
我的列表查看代码:
<ScrollView>
<ListView x:Name="ShipListView" HasUnevenRows="True" SeparatorVisibility="Default" SelectionMode="Single">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Grid Margin="4,3,4,3" Padding="2" BackgroundColor="White">
<Grid.RowDeFinitions HeightRequest="40">
<RowDeFinition></RowDeFinition>
<!--<RowDeFinition Height="20"></RowDeFinition>-->
</Grid.RowDeFinitions>
<Grid.ColumnDeFinitions>
<ColumnDeFinition Width="80*"></ColumnDeFinition>
<ColumnDeFinition Width="*"></ColumnDeFinition>
<ColumnDeFinition Width="40*"></ColumnDeFinition>
</Grid.ColumnDeFinitions>
<Label Text="{Binding ShipName}" TextColor="DeepPink" Grid.Column="0" FontAttributes="Bold"/>
<Switch IsToggled="{Binding Selected}" Grid.Column="2" Toggled="OnShipToggled" />
</Grid>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</ScrollView>
还有我的功能
async void OnShipToggled(object sender,ToggledEventArgs e)
{
checkShipSelected = !checkShipSelected;
if(checkShipSelected)
{
ViewCell cell = (sender as Switch).Parent.Parent as ViewCell;
ParametersMemberShipinformation model = cell.BindingContext as ParametersMemberShipinformation;
if (model != null)
{
selectedMemberShipOid = model.Oid;
}
}
else
{
return;
}
}
我正在尝试获取列表视图中所选项目的 id 并且我成功地做到了。但是我希望用户只能同时选择一个项目,因为视觉效果好,不要混淆。
解决方法
在你的代码隐藏文件中获取你的视图模型,然后过滤掉选定的切换并将其余的标记为假
private YourViewModel MyViewModel { get => BindingContext as YourViewModel; }
if (model != null)
{
selectedMemberShipOid = model.Oid;
MyViewModel.ShipListView.Where(x=> x.Oid !=
selectedMemberShipOid).Foreach(x=> x.Selected = false)
}