Setting the style of a WPF UserControl
You can directly set the UserControl's Style like this:
<UserControl x:Class="MyNamespace.MyControl" xmlns:local="MyNamespace" ...>
<UserControl.Style>
<Style>
<Setter Property="local:MyControl.MyProperty" Value="..."/>
...
</Style>
</UserControl.Style>
</UserControl>
or like this:
<UserControl x:Class="MyNamespace.MyControl" xmlns:local="MyNamespace" ...>
<UserControl.Style>
<Style TargetType="local:MyControl">
<Setter Property="MyProperty" Value="..."/>
...
</Style>
</UserControl.Style>
</UserControl>
A default Style in the UserControl's Resources should also work:
<UserControl x:Class="MyNamespace.MyControl" xmlns:local="MyNamespace" ...>
<UserControl.Resources>
<Style TargetType="local:MyControl">
<Setter Property="MyProperty" Value="..."/>
...
</Style>
</UserControl.Resources>
</UserControl>
Necro answer for a special case. If the user control is selected via a DataTemplate resource in another WPF control or window, WPF may not automagically apply a default style from an imported resource dictionary. However, you can apply named style resource after importing a resource dictionary.
<UserControl.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="../../Resources/ResourceDictionary.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</UserControl.Resources>
<UserControl.Style>
<Binding Source="{StaticResource MyUserControlStyle}"></Binding>
</UserControl.Style>
You need to remove the x:Key
from your defined style so that it can be applied universally to all controls of the same type as what is defined in the TargetType
.
To quote from MSDN for Style.TargetType Property:
Setting the TargetType property to the TextBlock type without setting an x:Key implicitly sets the x:Key to {x:Type TextBlock}. This also means that if you give the [...] Style an x:Key value of anything other than {x:Type TextBlock}, the Style would not be applied to all TextBlock elements automatically. Instead, you need to apply the style to the TextBlock elements explicitly.