Persisting Modern UI for WPF Styles






4.86/5 (6 votes)
Persisting modern UI for WPF Styles
Introduction
About 2 weeks ago, I blogged about Creating a Modern UI for WPF, the template by default doesn’t persist styles selected in the settings menu through application launches. So I’m going to give you the steps required to make this feature happen to complete feel of the template .
First, follow all the steps in the previous post, then you will need to add a new settings file to the project.
Next, you will need to add 4 settings:
- Name:
SelectedAccentColor
, Type:System.Windows.Media.Color
, Scope:User
, Value:#FF1BA1E2
- Name:
SelectedThemeSource
, Type:System.Uri
, Scope:User
, Value: /FirstFloor.ModernUI;component/Assets/ModernUI.Dark.xaml - Name:
SelectedThemeDisplayName
, Type:string
, Scope:User
, Value:dark
- Name:
SelectedFontSize
, Type:string
, Scope:User
, Value:large
Next, you will browse to Content\SettingsAppearanceViewModel.cs, add a private
member bool
called _colorLoadedYet
with a default value of false
.
private bool _colorLoadedYet;
Now look for a method called SyncThemeAndColor
and paste the code below at the bottom of that method:
if (this._colorLoadedYet)
{
ApplicationSettings.Default.SelectedThemeDisplayName = this.SelectedTheme.DisplayName;
ApplicationSettings.Default.SelectedThemeSource = this.SelectedTheme.Source;
ApplicationSettings.Default.SelectedAccentColor = this.SelectedAccentColor;
ApplicationSettings.Default.SelectedFontSize = this.SelectedFontSize;
ApplicationSettings.Default.Save();
}
Also, add a method called SetThemeAndColor
as below:
public void SetThemeAndColor
(string themeSourceDisplayName, Uri themeSourceUri, Color accentColor, string fontSize)
{
this.SelectedTheme = new Link
{ DisplayName = themeSourceDisplayName, Source = themeSourceUri };
this.SelectedAccentColor = accentColor;
this.SelectedFontSize = fontSize;
this._colorLoadedYet = true;
}
For the font size setting, we are going to go to the SelectedFontSize
property and code below after the line this.OnPropertyChanged(“SelectedFontSize”);
if (_colorLoadedYet)
{
ApplicationSettings.Default.SelectedFontSize = this.selectedFontSize;
ApplicationSettings.Default.Save();
}
And for the final step, you must browse to the MainWindow.xaml.cs file and just after the InitializeComponent
, add the code below:
SettingsAppearanceViewModel settings = new SettingsAppearanceViewModel();
settings.SetThemeAndColor(ApplicationSettings.Default.SelectedThemeDisplayName,
ApplicationSettings.Default.SelectedThemeSource,
ApplicationSettings.Default.SelectedAccentColor,
ApplicationSettings.Default.SelectedFontSize);
That’s all, you can now run your application and change the settings and they will persist through application launches. Through development, this will reset often but won’t while your application is used by a user. For the best results, replace the settings file with a more permanent storage location.