Automate Your App Settings View in WPF

 

If you’re anything like me, you’re always coming up with new ideas for applications. Since WPF is my favorite UI framework, I usually end up creating it in C# and WPF. Things go great for a while, the application gets to a working state and I’m ready to preview it to the world (or a friend), but there’s still one thing I need to do – the settings screen.

The requirements for a setting screen can vary depending on the complexity of your application, but even the simplest ones usually have a handful of settings. Every time I get to this stage of the process I end up slacking off and not really finishing it properly.

So, here’s my one-stop solution to never having to create another settings screen ever again. Just implement the steps below and you’ll have a simple settings screen that binds to a class with special attributes to handle some of the finer details. Let’s jump in –

Settings Classes

First we need a simple class to contain our settings. In this example we’ll just stick with 5 settings

public class AppSettings
{
    public string LogFile { get; set; }
    public bool LogAllData { get; set; }
    public bool LightTheme { get; set; }
    public int NumberOfUsers { get; set; }
    public enum eStartupView { get; set; }
}

Now, obviously, you’re probably storing these settings somewhere, either in SQL or some kind of file, but I’ll leave those details up to you.

We want to be able to add some data to these settings so we can display a description of the setting to the user on the Settings screen. There may be some other data you’ll need to add to them to organize the settings or even hide some from the user. To do this, we’re going to create an Attribute class –

public class SettingAttribute : Attribute
{
    public string Description { get; set; }
    public bool Visible { get; set; }
}

Now we can use this attribute class to add the extra information into our settings, so our AppSettings class becomes this

public class AppSettings
{
    [Settings(Description = "Log file location")]
    public string LogFile { get; set; }

    [Settings(Description = "Do you want to log all data?")]
    public bool LogAllData { get; set; }

    [Settings(Description = "Use the light theme?")]
    public bool LightTheme { get; set; }

    [Settings(Description = "How many users are in the system?)]
    public int NumberOfUsers { get; set; }

    [Settings(Description = "What view should we show on startup?")]
    public enum eStartupView { get; set; }
}

ViewModels

Now we can create the ViewModel for the Settings View. The goal in the SettingsViewModel is to read all the properties from AppSettings using reflection and create a list of SettingsItemViewModels. Let’s start with the SettingsItemViewModel. I have it inheriting from MVVMBase which is a base class that inherits INotifyPropertyChanged. If you’re looking for an MVVM framework may I suggest JustMVVM, I wrote it, but it’s the simplest MVVM framework around, and that’s why I did it.

public class SettingsItemViewModel : MVVMBase
{
    public string Name { get; set; }
    public string Description { get; set; }
    public Type SettingType { get; set; }
    public bool IsDirty { get; set; }

    private dynamic _value;
    public dynamic Value
    {
        get { return _value; }
        set
        {
            _value = value;
            OnPropertyChanged();

            IsDirty = true;
        }
    }
}

So, this class above is a generic class that can contain any type of setting. This way we can create a list of them, one for each of the properties in AppSettings. The real key to this is using the dynamic type for the property Value. It allows us to set it generically and then check if afterwards to find out the type. IsDirty can also be useful to tell if the setting was actually changed. We’ll see that below.

Here’s the code for the SettingsViewModel which is the view model for the SettingsView UI.

public class SettingsViewModel : MVVMBase
{
    private ObservableCollection<SettingsItemViewModel> _settings;
    public ObservableCollection<SettingsItemViewModel> Settings
    {
        get { return _settings; }
        set
        {
            _settings = value;
            OnPropertyChanged();
        }
    }

    public SettingsViewModel()
    {
        AppSettings appSettings = GetAppSettings();

        Settings = GetAvailableSettings(appSettings);
    }

    public ObservableCollection<SettingsItemViewModel> GetAvailableSettings(Dictionary<string, object> settings)
    {
        var settingsView = new ObservableCollection<SettingsItemViewModel>();

        foreach (var prop in typeof(AppSettings).GetProperties())
        {
            var settingItem = new SettingsItemViewModel();

            foreach (var customAttData in prop.GetCustomAttributesData())
            {
                foreach (var item in customAttData.NamedArguments)
                {
                    var name = item.MemberInfo.Name;

                    if (name == "Description")
                        settingItem.Description = item.TypedValue.Value.ToString();
                }
            }

            settingItem.Name = prop.Name;
            settingItem.Value = settings[prop.Name];

            // Get type once value is set, value will get type dynamically
            settingItem.SettingType = settingsItem.Value.GetType();

            settingItem.IsDirty = false;

            settingsView.Add(settingItem);
        }

        return settingsView;
    }
}

OK, we’ve now got our ObservableCollection<SettingsItemViewModel> ready to go for the View. Let’s take a look at what needs to happen there.

View

OK, the View is pretty straight forward. We’re going to use an ItemsControl to contain our list of settings and we’ll use DataTemplates to figure out what view to display for each setting. Hopefully this will become more clear after you look at the code –

<Grid>
    <ItemsControl ItemsSource="{Binding Settings}">        
        <ItemsControl.ItemTemplate>
            <DataTemplate DataType="{x:Type vm:SettingsItemViewModel}">
                <ContentControl Content="{Binding }">
                    <ContentControl.Style>
                        <Style TargetType="{x:Type ContentControl}">
                            <Style.Triggers>

                                <DataTrigger Binding="{Binding SettingType}"
                                             Value="{x:Type sys:Boolean}">
                                    <Setter Property="ContentTemplate" Value="{StaticResource BooleanSettingTemplate}" />
                                </DataTrigger>

                                <DataTrigger Binding="{Binding SettingType}"
                                             Value="{x:Type sys:Int32}">
                                    <Setter Property="ContentTemplate" Value="{StaticResource IntegerSettingTemplate}" />
                                </DataTrigger>

                                <DataTrigger Binding="{Binding SettingType}"
                                             Value="{x:Type sys:Double}">
                                    <Setter Property="ContentTemplate" Value="{StaticResource DoubleSettingTemplate}" />
                                </DataTrigger>

                                <DataTrigger Binding="{Binding SettingType}"
                                             Value="{x:Type sys:String}">
                                    <Setter Property="ContentTemplate" Value="{StaticResource StringSettingTemplate}" />
                                </DataTrigger>

                                <DataTrigger Binding="{Binding SettingType,
                                                               Converter={StaticResource IsEnumeratorConverter}}"
                                             Value="True">
                                    <Setter Property="ContentTemplate" Value="{StaticResource EnumSettingTemplate}" />
                                </DataTrigger>

                            </Style.Triggers>
                        </Style>
                    </ContentControl.Style>
                </ContentControl>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>
</Grid>

The ContentControl inside the ItemsControl has a bunch of triggers that displays a different DataTemplate based on the SettingType of the SettingsItem. This allows us to have different views for each type. Obviously the view for a Boolean settings will be some kind of a checkbox, while the view for an enum would probably be a combobox.

Here are the data templates used to make this magic happen. If you don’t know too much about data templates, this is a good resources. These need to be placed in the resources section somewhere in the View. In this case I put it in the ItemsControl.Resources section.

<ItemsControl.Resources>

    <DataTemplate x:Key="BooleanSettingTemplate">
        <UniformGrid Columns="2"
                     Rows="1">
            <Label HorizontalAlignment="Right"
                   Content="{Binding Description}" />
            <CheckBox HorizontalAlignment="Left"
                      Content=""
                      IsChecked="{Binding Value}" />
        </UniformGrid>
    </DataTemplate>

    <DataTemplate x:Key="IntegerSettingTemplate">
        <UniformGrid Columns="2"
                     Rows="1">
            <Label HorizontalAlignment="Right"
                   Content="{Binding Description}" />
            <wpf:SFNumberTextBox HorizontalAlignment="Left"
                                 Interval="1"
                                 StringFormat="N0"
                                 ValueInt="{Binding Value}" />
        </UniformGrid>
    </DataTemplate>

    <DataTemplate x:Key="DoubleSettingTemplate">
        <UniformGrid Columns="2"
                     Rows="1">
            <Label HorizontalAlignment="Right"
                   Content="{Binding Description}" />
            <wpf:SFNumberTextBox HorizontalAlignment="Left"
                                 Interval="0.5"
                                 StringFormat="N1"
                                 Value="{Binding Value}" />
        </UniformGrid>
    </DataTemplate>

    <DataTemplate x:Key="StringSettingTemplate">
        <UniformGrid Columns="2"
                     Rows="1">
            <Label HorizontalAlignment="Right"
                   Content="{Binding Description}" />
            <TextBox HorizontalAlignment="Left"
                     wpfab:TextFieldExt.ClearTextButton="True"
                     Text="{Binding Value}" />
        </UniformGrid>
    </DataTemplate>

    <DataTemplate x:Key="EnumSettingTemplate">
        <UniformGrid Columns="2"
                     Rows="1">
            <Label HorizontalAlignment="Right"
                   Content="{Binding Description}" />
            <ComboBox ItemsSource="{Binding SettingType,
                                            Converter={StaticResource EnumToArrayConverter}}"
                      SelectedItem="{Binding Value}" />
        </UniformGrid>
    </DataTemplate>

</ItemsControl.Resources>

Alright. Everything’s linked up now. Obviously you can add to this if you have more complicated settings. Some settings may even be complete other classes. Either way, this setup should work pretty smoothly for you.

Converters

Here’s a couple of extra pieces that make it easier to use enums with comboboxes for settings (I’m assuming you have some). They’re just a couple of simple converters that let you bind to an enum without having to explicitly mention the enum type.

public class IsEnumeratorConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (!(value is Type))
            return false;

        var type = value as Type;

        return type.IsEnum;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}


public class EnumToArrayConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (!(value is Type))
            return new List<string>();

        return Enum.GetValues(value as Type);
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

That’s it. Let me know what you think in the comments. I’m always looking for feedback. I’ve been thinking of some variation of this setup for a while now, and I’m looking forward to never manually creating another settings screen ever again.

Advertisements

DataContext, Data Templates and Data Template Selectors

I spent some time today working on DataTemplateSelectors. I’d never used them before, but it made me think about all the different ways there are to set the DataContext in WPF. After talking through this with a friend, I realized that maybe some of these minor nuances aren’t very clear. I figured if I write about it, at least I can reference it again later when I forget.

OK, my first assumption here is that you’re being a good programmer and using MVVM, this is WPF after all.

Binding To Code-Behind

This is the most basic kind of binding. When you first learn MVVM, this is probably going to be your first step. Binding to code-behind just requires you to set your DataContext to the xaml.cs file attached to your View –

<Window .....
        DataContext="{Binding RelativeSource={RelativeSource Self}}">           
</Window>

In the long run I don’t recommend this one, you’re always going to want to bind a View to a ViewModel in a separate class. It just makes it so much cleaner. This leads to my next header

Binding To ViewModel

This one is really similar to binding to your code behind. The only difference here is that instead of binding to yourself, you’re binding to your View Model. Simple right, OK, here’s the code –

<Window x:Class="MyProgram.MainWindow"
        xmlns:local="clr-namespace:MyProgram"
        mc:Ignorable="d">

    <Window.DataContext>
        <local:MainWindowViewModel />
    </Window.DataContext>
</Window>

Make sure to get the correct namespace (in this case local) of your View Model. When using this style of datacontext setting, you’re going to have to do this for each and every View. At first this might seem OK, but the further into this you get, the more cumbersome this method becomes.

OK, onto the next method; DataTemplates!

Binding Using DataTemplates

DataTemplates are used all over WPF (seriously, you should take a look into how awesome data templating is in ListViews if you don’t believe me). When it comes to Views and View Models the data template allows you to load your Views by specifying the View Model you want. Instead of loading View first, you can call the View Model (along with it’s constructor) and the ContentPresenter will figure out what View to serve up alongside it.

The beauty of this is you can now pass around data between your view models, making it easier to structure your program.

You still need to set the DataContext of your initial entry point View. In the case above it’s the MainWindow and MainWindowViewModel. So, even in this method, make sure to set the DataContext first.

Now, add some kind of presenter (it can be a ContentPresenter, ContentControl or UserControl). This will be the View Controller that will change out the different views according to your bindings. Here’s the code for the View –

<Window x:Class="MyProgram.MainWindow"
        xmlns:local="clr-namespace:MyProgram"
        mc:Ignorable="d">

    <Window.DataContext>
        <local:MainWindowViewModel />
    </Window.DataContext>

    <Grid>
        <ContentPresenter Content="{Binding View}" />
    </Grid>
</Window>

Here’s the code for your View Model (I’m not including the INotifyPropertyChanged interface, I’m assuming you’ve got that figured out by now, but if you’re looking for a framework, try JustMVVM). MVVMBase is just a base class that all View Models must inherit from.

class MainWindowViewModel : MVVMBase
{
    private MVVMBase _currentViewModel;
    public MVVMBase CurrentViewModel
    {
        get { return _currentViewModel; }
        set
        {
                _currentViewModel = value;
                OnPropertyChanged();
        }
    }

    public MainWindowViewModel()
    {
        // Setting View to Home screen
        CurrentViewModel = new HomeViewModel();
    }
}

For the application to figure out what view to load for the ContentPresenter, we need to add a Data Template. The simplest place to put this is in App.xaml, then it’ll work throughout the entire application, but in reality you can put this in any Resources section

Below are 3 different data templates for 3 different views.

<Application x:Class="MyProgram.App"
             xmlns:view="clr-namespace:MyProgram.View"
             xmlns:viewmodel="clr-namespace:MyProgram.ViewModel"
             Startup="Application_Startup"
             StartupUri="MainWindow.xaml">

    <Application.Resources>

        <DataTemplate DataType="{x:Type viewmodel:HomeViewModel}">
            <view:Home />
        </DataTemplate>

        <DataTemplate DataType="{x:Type viewmodel:SettingsViewModel}">
            <view:Settings />
        </DataTemplate>

        <DataTemplate DataType="{x:Type viewmodel:HelpViewModel}">
            <view:Help />
        </DataTemplate>

    </Application.Resources>
</Application>

For most of my applications that I’ve worked on, this has worked out great. I have a single spot where I put all my data templates and then I’m in complete control over what views are being loaded. There are occasional situations that require an even more complicated solution, so here we go, my final option, the DataTemplateSelector.

Data Template Selector

In theory this is another alternative to using Data Templates, but it gives a little more control over the issue. Sometimes a need arises where you have multiple Views for a single View Model, or you’ve created a generic form of ViewModel<T> but you can’t define a DataTemplate for generics in XAML. In this case, you can create a Data Template Selector, which allows you to select the associated View template in code.

Here’s some example code of the Selector –

public class CustomDataTemplateSelector : DataTemplateSelector
{
    public DataTemplate HomeTemplate { get; set; }
    public DataTemplate SettingsTemplate { get; set; }
    public DataTemplate HelpTemplate { get; set; }

    public override DataTemplate SelectTemplate(object item, DependencyObject container)
    {
        if (item == null)
            return base.SelectTemplate(item, container);

        var viewModel = item as PropertyChangedBase;
        var viewModelType = viewModel.GetType();

        if (viewModelType.IsGenericType && viewModelType.GetGenericTypeDefinition() == typeof(HomeViewModel<>))
                return HomeTemplate;

        else if (viewModelType == typeof(SettingsViewModel))
            return SettingsTemplate;

        else if (viewModelType == typeof(HelpViewModel))
            return HelpTemplate;

        else
            return base.SelectTemplate(item, container);
    }
}

Let’s unpack this a little bit. The properties at the top can be set in the XAML to the data templates we created in the previous section (see below for how it’s done). The first part of the if statement shows how you can handle a generic type for a template selector. This means that any HomeViewModel<T> will load the HomeTemplate.

The reason I ended up using this over Data Templates is for the else part at the end. I was creating a library that was to be consumed by others. I wanted to be very specific about what templates were loaded in my library, but also leave open the possibility of other people adding their own templates. I guess I could have created some extensible class that allows people to add more templates, but by calling the base implementation of the DataTemplateSelector

return base.SelectTemplate(item, container);

I don’t have to do anything special, I just let the normal DataTemplates take over again like usual.

Here’s how this Selector was implemented in XAML –

<Grid>
    <Grid.Resources>

        <DataTemplate x:Name="HomeTemplate" >
            <view:Home />
        </DataTemplate>

        <DataTemplate x:Name="SettingsTemplate" >
            <view:Settings />
        </DataTemplate>

        <DataTemplate x:Name="HelpTemplate" >
            <view:Help />
        </DataTemplate>

        <viewmodel:CustomDataTemplateSelector x:Key="ViewTemplateSelector"
                                              HomeTemplate="{StaticResource dialogException}"
                                              SettingsTemplate="{StaticResource dialogOKCancel}"
                                              HelpTemplate="{StaticResource dialogOK}" />

    </Grid.Resources>

    <!--  Dialog User Control  -->
    <ContentPresenter Content="{Binding View}"
                      ContentTemplateSelector="{StaticResource ViewTemplateSelector}" />
</Grid>

And like I said, any other View / View Model templates can either be added to the Template Selector (if you have access to it) or can just be placed in App.xaml like usual.

Well, I think that’s all I’ve got about Data Templates. Hopefully by putting this all together in one place I’ve made somebody’s life easier. If you see anything wrong, let me know in the comments.