至少保留几个Xamarin开关之一?

问题描述 投票:0回答:2

我不希望用户不选择至少一个主题就可以开始测验。

如何确保至少切换了一个开关?

UI

Xaml:

    <StackLayout Margin="20,35,20,20">
    <Entry x:Name="nameEntry"
           Placeholder="Enter name" />
    <Label Text="Math"/>
    <Switch Toggled="Switcher_Toggled" ClassId="Math"/>
    <Label Text="History"/>
    <Switch Toggled="Switcher_Toggled" ClassId="History"/>
    <Button x:Name="StartButton" Clicked="OnStartButtonClicked" Text="Start Quiz"/>
</StackLayout>

Xaml.cs:

void Switcher_Toggled(object sender, ToggledEventArgs e)
{
    var switchItem = (Switch)sender;
    if (!e.Value)
    {
        SelectedCategories.categories.Remove(switchItem.ClassId);
    }

    else
    {
        SelectedCategories.categories.Add(switchItem.ClassId);

    }
}     

很简单。那么,对此的实际解决方案是什么?

c# xaml xamarin switch-statement
2个回答
0
投票

最简单的方法是计算SelectedCategories

if( SelectedCategories.Count > 0 ){

您可能希望对Add进行一次检查,以检查是否两次添加了相同的ClassId,这取决于调用它的方式和方式。


0
投票

以下代码仅对我有用。当没有切换开关时,它仅限制执行任何逻辑。

//XAML code
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             mc:Ignorable="d"
             x:Class="Demo.MainPage">

    <StackLayout Margin="20,35,20,20">
        <Entry x:Name="nameEntry" Placeholder="Enter name" />
        <Label Text="Math"/>
        <Switch x:Name="Math" Toggled="Switcher_Toggled" ClassId="Math" />
        <Label Text="History"/>
        <Switch x:Name="History" Toggled="Switcher_Toggled" ClassId="History"/>
        <Button x:Name="StartButton" Clicked="OnStartButtonClicked" Text="Start Quiz"/>
    </StackLayout>
</ContentPage>

//XAML code behind logic.
public partial class MainPage : ContentPage
{
    public List<string> SelectedCategories { get; set; }
    public MainPage()
    {
        InitializeComponent();
        this.SelectedCategories = new List<string>();
    }

    private void OnStartButtonClicked(object sender, EventArgs e)
    {
        if (this.Math.IsToggled || this.History.IsToggled)
        {
            this.DisplayAlert("Alert", "Quiz Started..!", "OK");
        }
    }

    private void Switcher_Toggled(object sender, ToggledEventArgs e)
    {
        var switchItem = (Switch)sender;
        if (!e.Value)
        {
            SelectedCategories.Remove(switchItem.ClassId);
        }
        else
        {
            SelectedCategories.Add(switchItem.ClassId);
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.