MAUI IOS - 单选按钮在页面初始加载时不会显示选中状态

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

我的应用程序中有一个页面,用单选按钮显示数据。正如预期的那样,当页面加载时,其中之一应该显示为选中状态,但无论我做什么,所有单选按钮都显示为未选中状态。这是我的单选按钮定义。我应该提到这是在 CollectionView 中,它是 3 个属性之一。同样,每个按钮针对每一行显示,但没有一个显示选定。

 <RadioButton x:Name="RbSelect" Grid.Column="6" Grid.Row="0"
 CheckedChanged="RadioButton_CheckedChanged"
 GroupName="RadioGroup" IsChecked="{Binding RbSelected}">
 <RadioButton.Content>
     <StackLayout>
         <Label
             Margin="30,0,0,0"                                            
             TextColor="{StaticResource FieldNameTextColor}"
             VerticalOptions="Start" />
     </StackLayout>
 </RadioButton.Content>

这是我尝试设置值的代码。这是我最新的尝试,但是,我尝试了很多不同的解决方案。

    public UpdateCars(ObservableCollection<AutoWithSwitch> value, CollectionView updateCarsViewModel)
{           
    InitializeComponent();           
    updateCarsViewModel.ItemsSource = null;           
    
    foreach (var item in value)
    {
        if (item.IsChecked)
            RbSelect.IsChecked = true;
        else
            RbSelect.IsChecked = true;
    }
    updateCarsViewModel.ItemsSource = value;
}
c# ios radio-button maui
1个回答
0
投票

您的代码显示了一个

bool
绑定:
IsChecked="{Binding RbSelected}
并且您需要确保该属性在绑定上下文类中初始化为
true
,并且在更改时会触发
PropertyChanged
通知。在这种情况下应该有效。换句话说,确保当通过 xaml 或代码设置
BindingContext
时,该值已经为 true。


然而,“繁荣”比生存更好。作为替代方案,请考虑单选按钮暗示一组可以用

enum: 表示的选项

enum CarType
{
    Tesla,
    Audi,
    Porsche,
}

假设您有一些
BindingContext
,其属性为

CarType

,并且 
is
CarType,并且该属性会触发 PropertyChanged
class MainPageBindingContext : INotifyPropertyChanged
{
    public CarType CarType
    {
        get => _carType;
        set
        {
            if (!Equals(_carType, value))
            {
                _carType = value;
                OnPropertyChanged();
            }
        }
    }
    CarType _carType = CarType.Tesla;

    public event PropertyChangedEventHandler PropertyChanged;
    private void OnPropertyChanged([CallerMemberName] string propertyName = null) =>
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

问题是,您的
RadioButton
实例可以直接绑定到此

enum

。这不仅可以解决您的“初始加载”问题,我们还可以(例如)通过单击按钮来设置选择...

...

通过单选选择设置按钮文本。

修改了MAUI默认MainPage xaml


此 xaml 前向引用其下面定义的
EnumToBooleanConverter

类。

<ContentPage 
    xmlns="http://schemas.microsoft.com/dotnet/2021/maui"             
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"             
    xmlns:local ="clr-namespace:maui_radio_buttons"             
    x:Class="maui_radio_buttons.MainPage">
    <ContentPage.BindingContext>
        <local:MainPageBindingContext/>
    </ContentPage.BindingContext>
    <ContentPage.Resources>
        <ResourceDictionary>
            <local:EnumToBooleanConverter x:Key="EnumToBoolConverter" />
        </ResourceDictionary>
    </ContentPage.Resources>
    <ScrollView>
        <VerticalStackLayout
            Spacing="25"
            Padding="30,0"
            VerticalOptions="Center">
            <Image
                Source="dotnet_bot.png"
                SemanticProperties.Description="Cute dot net bot waving hi to you!"
                HeightRequest="200"
                HorizontalOptions="Center" />
            <Button
                x:Name="CounterBtn"
                Text="Click me"
                SemanticProperties.Hint="Counts the number of times you click"
                Clicked="OnCounterClicked"
                HorizontalOptions="Center" />
            <RadioButton
                GroupName="RadioGroup"
                IsChecked="{Binding CarType, Converter={StaticResource EnumToBoolConverter}, ConverterParameter=Tesla}">
                <RadioButton.Content>
                    <Label 
                        Text="Tesla" 
                        TextColor="{StaticResource Primary}" 
                        Margin="30,0,0,0" ></Label>
                </RadioButton.Content>
            </RadioButton>
            <RadioButton
                GroupName="RadioGroup"
                IsChecked="{Binding CarType, Converter={StaticResource EnumToBoolConverter}, ConverterParameter=Audi}">
                <RadioButton.Content>
                    <Label 
                        Text="Audi"
                        TextColor="{StaticResource Primary}" 
                        Margin="30,0,0,0" ></Label>
                </RadioButton.Content>
            </RadioButton>
            <RadioButton
                GroupName="RadioGroup"
                IsChecked="{Binding CarType, Converter={StaticResource EnumToBoolConverter}, ConverterParameter=Porsche}">
                <RadioButton.Content>
                    <Label 
                        Text="Porsche"
                        TextColor="{StaticResource Primary}" 
                        Margin="30,0,0,0" ></Label>
                </RadioButton.Content>
            </RadioButton>
        </VerticalStackLayout>
    </ScrollView>
</ContentPage>

IValueConverter类

这个简单的转换器查看是否可以从 MainPage.xaml 中定义的
CarType
的值解析

ConverterParameter

 的当前值。
public class EnumToBooleanConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value == null || parameter == null)
            return false;
        string enumValue = value.ToString();
        string targetValue = parameter.ToString();
        return enumValue.Equals(targetValue, StringComparison.InvariantCultureIgnoreCase);
    }
    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is bool && (bool)value)
        {
            return Enum.Parse(targetType, parameter.ToString(), true);
        }
        return Binding.DoNothing;
    }
}

修改了MAUI默认MainPage C#

public partial class MainPage : ContentPage { int count = 0; bool isButtonClicking = false; public MainPage() { InitializeComponent(); // Just for fun, we'll use the `PropertyChanged` // notification of `CarType` to change the button text. BindingContext.PropertyChanged += (sender, e) => { if(e.PropertyName == nameof(MainPageBindingContext.CarType) && !isButtonClicking) { CounterBtn.Text = BindingContext.CarType.ToString(); } }; } private void OnCounterClicked(object sender, EventArgs e) { count++; string token = (count == 1) ? "time" : "times"; CounterBtn.Text = $"Clicked {count} {token}"; SemanticScreenReader.Announce(CounterBtn.Text); isButtonClicking = true; BindingContext.CarType = (CarType)((Convert.ToInt16(BindingContext.CarType) + 1) % 3); isButtonClicking = false; } new MainPageBindingContext BindingContext => (MainPageBindingContext)base.BindingContext; }

© www.soinside.com 2019 - 2024. All rights reserved.