Reputation: 5444
I've been writing a CAD-style program in .Net, for this I have to have a lot of Brushes
and Custom DashStyles
.
So far I have defined them in a static
class. for example:
public static readonly Brush GridBrushInModel = Brushes.DarkGray;
Now I can use the brush whenever I want. I have also Freezed them though.
My question is, is this the way this should be done? Or there are better ways? For example defining in ResourceDictionary
? How it is done?
Upvotes: 3
Views: 1043
Reputation: 61339
Shared resources in a WPF application are typically stored as a ResourceDictionary
. Each dictionary should have its own XAML file (if you wish to split up your resources).
They are pretty easy to define:
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<SolidColorBrush x:Key="MyCoolBrush" Color="Black"/>
</ResourceDictionary>
Note that I gave the element a x:Key
attribute. This is what you use to reference the resource later.
Finally, you have to merge the dictionary into the using code. This can be done at any level, though its most commonly done in the Window.Resources
or in App.xaml
.
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Resources/MyBrushes.xaml"/>
</ResourceDictionary.MergedDictionaries>
...
</ResourceDictionary>
</Window.Resources>
Once you have them, you can reference them in XAML like this:
<Grid Background={StaticResource MyCoolBrush}/>
Upvotes: 4