WPF Basics: General Global Styles for MVVM

I am trying to use the MVVM-ish approach to my WPF development.

I have classes of a logical presentation model in the ViewModel namespace, and I have an appropriate style for these view model classes in the View namespace.

At the moment, I have my View information in XAML ResourceDictionary files, like DataTemplates and Styles, which are all combined into one App.Resources ResourceDictionary file in app.xaml.

However, I ran into a chicken / egg problem. I want global styles that I use everywhere. For example, I need my own custom text style called MonkeyText, which can be used in different styles everywhere. I cannot just install this in the app.xaml file because the resourcedictionarys that want to use MonkeyText are included in this app.xaml file.

I think if this is not possible, an alternative would be to use UserControls instead of mainly using DataTemplates to define my views? I am afraid that using UserControls will too closely link parts of VM and V.

+6
c # wpf mvvm xaml
source share
1 answer

WPF provides DynamicResources for this very reason. StaticResources - which are most reminiscent of the "traditional" links in programming - there is only the problem you are facing; they must be defined and loaded before the style is analyzed. On the other hand, DynamicResources need not be defined until they are used - indeed, you can even create them on the fly. WPF makes sure that DynamicResources is automatically loaded with all styles that reference them after they are actually loaded.

Using DynamicResources is simple. When you create a MonkeyText style, create it as usual:

<Style TargetType="TextBlock" x:Key="MonkeyText"> <Setter Property="TextAlignment" Value="Center"/> <!-- etc. --> </Style> 

And then access it from another source using DynamicResource:

 <TextBlock Text="Hello, World!" Style="{DynamicResource MonkeyText}"/> 

If for some reason WPF cannot resolve your DynamicResource, it will fail without any exceptions (StaticResources really throw exceptions if they cannot be resolved). However, it will print a debugging message when this happens - keep an eye on the output window in Visual Studio.

Since DynamicResources work with resources that are loaded at any time in any order, you can structure your resource dictionaries in any way you like - thus, inserting them into your other view styles and combining them through a single App.Resources ResourceDictionary file in app.xaml will work fine.

More about DynamicResources can be found in the MSDN docs for WPF.

+10
source share

All Articles