Search code examples
c#winrt-xamlwin-universal-apptemplate10

Binding to Template10 Settings from Main Page


I am loving Template10 so far, very nice. I am a little stuck though on how to bind to a Setting value on the Main Page. I have added a new bool setting which is storing properly. On my main page I have a Visibility binding to the setting:

Visibility="{Binding UseAmbientLightSensor, Converter={StaticResource CollapsedWhenFalseConverter}}"

This works on app start as expected, the MainPageViewModel reads the value from Settings and a grid is visible or collapsed based on that setting.

However I cannot seem to get this binding to 'listen' to the setting, if I go to the settings page and change that value, when I go back to the Main Page the visibility does not change. It only works if I restart the app.

In the vanilla Template10 install this would be akin to Binding a little logo on MainPage to the 'UseLightThemeButton' setting in the Settings page which changes based on that setting..


Solution

  • Okay, so I guess this is the "official" answer. But many approaches are valid. This one matches most closely to the templates. I would do it like this:

    public class MainPageViewModel : ViewModelBase
    {
        Services.SettingService.SettingService _SettingService;
    
        public MainPageViewModel()
        {
            _SettingService = Services.SettingService.SettingService.Instance;
        }
    
        public override async Task OnNavigatedToAsync(object parameter, NavigationMode mode, IDictionary<string, object> state)
        {
            Windows.Storage.ApplicationData.Current.DataChanged += SettingsChanged;
            await Task.CompletedTask;
        }
    
        public override async Task OnNavigatedFromAsync(IDictionary<string, object> pageState, bool suspending)
        {
            Windows.Storage.ApplicationData.Current.DataChanged -= SettingsChanged;
            await Task.CompletedTask;
        }
    
        private void SettingsChanged(Windows.Storage.ApplicationData sender, object args)
        {
            RaisePropertyChanged(nameof(FontSize));
        }
    
        public double FontSize { get { return _SettingService.FontSize; } }
    }
    

    With that view-model, you can easily bind to a setting (in this case FontSize).

    Best of luck.