question

DiamondKesha avatar image
0 Votes"
DiamondKesha asked DiamondKesha edited

Xamarin.Forms Didn't binding value in RadioButton by method with returned value

I have three RadioButtons with Value: System, Light and Dark. In the initialization of the ViewModel, I get the value using the GetReferenceValueOrDefault method (it returns System, Light or Dark depending on the user's preferences). In this case, "System" is returned.

126202-photo-2021-08-22-16-29-22.jpg



But when I bind the value using this method, then the RadioButton is not activated. But, if I write the System method instead, it is activated. What could be the problem?

ViewMode code:

 public class SettingsViewModel : BaseViewModel
     {
    
         private readonly ILanguageService _languageService;
         private readonly ISettingsService _settingsService;
    
         public SettingsViewModel(ILanguageService languageService, ISettingsService settingsService)
         {
             _languageService = languageService;
             _settingsService = settingsService;
         }
    
         public override Task InitializeAsync(object parameter)
         {
                
             InterfaceLanguageList = _languageService.GetAvailableInterfaceLanguages();
             int index = InterfaceLanguageList.ToList().FindIndex(x => x.TwoLetterISOLanguageName.Equals(_languageService.GetCurrentInterfaceLanguage()));
             if (index != -1) SelectedInterfaceLanguage = InterfaceLanguageList[index];
    
             TitleLanguageList = _languageService.GetAvailableTitleLanguages();
             index = TitleLanguageList.ToList().FindIndex(x => x.TwoLetterISOLanguageName.Equals(_languageService.GetCurrentTitleLanguage()));
             if (index != -1) SelectedTitleLanguage = TitleLanguageList[index];
                
    
             // didnt work, this method returned "System" value
             SelectedAppTheme = _settingsService.GetPreferencesValueOrDefault(GlobalValues.SettingsThemeKey, GlobalValues.SettingsThemeDefaultValue);
    
             // work
             //SelectedAppTheme = "System";
    
             return base.InitializeAsync(parameter);
         }
    
         #region Variables 
    
         private ObservableCollection<Models.Language> _interfaceLanguageList;
         public ObservableCollection<Models.Language> InterfaceLanguageList
         {
             get => _interfaceLanguageList;
             set => SetProperty(ref _interfaceLanguageList, value);
         }
    
         private Models.Language _selectedInterfaceLanguage;
         public Models.Language SelectedInterfaceLanguage
         {
             get => _selectedInterfaceLanguage;
             set
             {
                 if(value.TwoLetterISOLanguageName != _languageService.GetCurrentInterfaceLanguage()) _languageService.ChangeInterfaceLanguage(value); // optimize?
                 SetProperty(ref _selectedInterfaceLanguage, value);
             }
         }
    
    
         private ObservableCollection<Models.Language> _titleLanguageList;
         public ObservableCollection<Models.Language> TitleLanguageList
         {
             get => _titleLanguageList;
             set => SetProperty(ref _titleLanguageList, value);
         }
    
         private Models.Language _selectedTitleLanguage;
         public Models.Language SelectedTitleLanguage
         {
             get => _selectedTitleLanguage;
             set
             {
                 if (value.TwoLetterISOLanguageName != _languageService.GetCurrentInterfaceLanguage()) _languageService.ChangeTitleLanguage(value); // optimize?
                 SetProperty(ref _selectedTitleLanguage, value);
             }
         }
    
         private object _selectedAppTheme;
         public object SelectedAppTheme
         {
             get => _selectedAppTheme;
             set => SetProperty(ref _selectedAppTheme, value);
         }
    
         #endregion Variables
    
         #region Commands
    
         public ICommand RadioButtonCheckedChangedCommand => new Command<object>(RadioButtonCheckedChanged);
         private void RadioButtonCheckedChanged(object parameters)
         {
    
             string themeValue = (parameters as RadioButton)?.Value.ToString();
    
             if (_settingsService.GetPreferencesValueOrDefault(GlobalValues.SettingsThemeKey, GlobalValues.SettingsThemeDefaultValue) == themeValue) return;
    
             _settingsService.AddOrUpdatePreferencesValue(GlobalValues.SettingsThemeKey, themeValue);
             AppThemeController.Set(themeValue);
         }
    
         #endregion Commands
     }

Xaml code:

<Grid
ColumnDefinitions=",,*"
ColumnSpacing="10"
RadioButtonGroup.GroupName="AppThemeGroup"
RadioButtonGroup.SelectedValue="{Binding SelectedAppTheme}">
<RadioButton
x:Name="RadioButtonThemeSystem"
ControlTemplate="{StaticResource ThemeRadioTemplate}"
HorizontalOptions="Center"
Value="System">

                             <RadioButton.Behaviors>
                                 <toolkit:EventToCommandBehavior
                                     Command="{Binding RadioButtonCheckedChangedCommand}"
                                     CommandParameter="{x:Reference RadioButtonThemeSystem}"
                                     EventName="CheckedChanged" />
                             </RadioButton.Behaviors>

                             <RadioButton.Content>
                                 <StackLayout HorizontalOptions="Center" VerticalOptions="Center">
                                     <Image Scale="1.15" Source="outline_settings_suggest_24" />
                                     <Label Text="System" />
                                 </StackLayout>
                             </RadioButton.Content>
                         </RadioButton>

                         <RadioButton
                             x:Name="RadioButtonThemeLight"
                             Grid.Column="1"
                             ControlTemplate="{StaticResource ThemeRadioTemplate}"
                             HorizontalOptions="Center"
                             Value="Light">

                             <RadioButton.Behaviors>
                                 <toolkit:EventToCommandBehavior
                                     Command="{Binding RadioButtonCheckedChangedCommand}"
                                     CommandParameter="{x:Reference RadioButtonThemeLight}"
                                     EventName="CheckedChanged" />
                             </RadioButton.Behaviors>

                             <RadioButton.Content>
                                 <StackLayout HorizontalOptions="Center" VerticalOptions="Center">
                                     <Image Scale="1.15" Source="outline_light_mode_24" />
                                     <Label Text="Light" />
                                 </StackLayout>
                             </RadioButton.Content>
                         </RadioButton>

                         <RadioButton
                             x:Name="RadioButtonThemeDark"
                             Grid.Column="2"
                             ControlTemplate="{StaticResource ThemeRadioTemplate}"
                             HorizontalOptions="Center"
                             Value="Dark">

                             <RadioButton.Behaviors>
                                 <toolkit:EventToCommandBehavior
                                     Command="{Binding RadioButtonCheckedChangedCommand}"
                                     CommandParameter="{x:Reference RadioButtonThemeDark}"
                                     EventName="CheckedChanged" />
                             </RadioButton.Behaviors>

                             <RadioButton.Content>
                                 <StackLayout HorizontalOptions="Center" VerticalOptions="Center">
                                     <Image Scale="1.15" Source="outline_dark_mode_24" />
                                     <Label Text="Dark" />
                                 </StackLayout>
                             </RadioButton.Content>
                         </RadioButton>
                     </Grid>


dotnet-xamarin
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

JarvanZhang-MSFT avatar image
1 Vote"
JarvanZhang-MSFT answered DiamondKesha edited

Hello,​

Welcome to our Microsoft Q&A platform!

didnt work, this method returned "System" value

Does the 'settingsService.GetPreferencesValueOrDefault' return ‘System’ result? I tested a basic demo to test the function, it works as expected. Will the command take a few time to be operated? Please try adding the await keyword to wait the method to be completed.

public async override Task InitializeAsync(object parameter)
{
    ...
    // didnt work, this method returned "System" value
    SelectedAppTheme = await _settingsService.GetPreferencesValueOrDefault(GlobalValues.SettingsThemeKey, GlobalValues.SettingsThemeDefaultValue);

    // work
    //SelectedAppTheme = "System";
    return base.InitializeAsync(parameter);
}


Best Regards,

Jarvan Zhang


If the response is helpful, please click "Accept Answer" and upvote it.

Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


· 8
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Hello! This solution does not work for me :(
Yes, this method returned "System".126350-yyh7i607z6u.jpg




I'm try using latest and *.2012 version xamarin.forms. When i'm delete cache and data app in my mobile, then the first time the page is opened, the RadioButton is activated, but when I close and open again the page, it is no longer activated

0 Votes 0 ·
yyh7i607z6u.jpg (21.5 KiB)

Hi, @DiamondKesha . I also tested the code on Xamarin.Forms 5.0.0.2012, it works fine. It seems there is nothing wrong with the package version. You could also update the Xamarin.Forms nuget to lastest stable version 5.0.0.2012 for test.

then the first time the page is opened, the RadioButton is activated, but when I close and open again the page, it is no longer activated

Could you post more details about the 'GetReferenceValueOrDefault' method? Is it from an api service? If it's just a until class, please share the related code about the method.

0 Votes 0 ·

Hi. I have already latest version Xamarin.Forms.
Code of method GetReferenceValueOrDefault:

     public async Task<string> GetPreferencesValueOrDefault(string key, string defaultValue)
     {
         if (!Preferences.ContainsKey(key))
         {
             AddOrUpdatePreferencesValue(key, defaultValue);
             return defaultValue;
         }

         return Preferences.Get(key, defaultValue);
     }

Method AddOrUpdatePreferencesValue:

     public void AddOrUpdatePreferencesValue(string key, string value)
     {
         if (string.IsNullOrEmpty(value)) Preferences.Remove(key);

         Preferences.Set(key, value);
     }


0 Votes 0 ·
Show more comments