How to apply Style programmatically in CustomControl

I have a custom ColorPickerButton button in WPF, and the "ColorPickerButtonStyle" style has been applied to it, which I have to apply in xmal as follows;

<UserControl.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="RD_ColorThemes.xaml"/>
           <ResourceDictionary Source="RDColorPicker.xaml"/>
        </ResourceDictionary.MergedDictionaries> 
    </ResourceDictionary>
</UserControl.Resources>

<Grid x:Name="grd">
<cp:ColorPickerButton x:Name="btn" Width="25" Height="25" 
Style="{DynamicResource ColorPickerButtonStyle}" 
Click="ColorPickerButton_Click" />

it works fine. But if I forget to apply the style {DynamicResource ColorPickerButtonStyle}, the button will look like a deadly fish. Here I am trying to apply this part of <ResourceDictionary Source = "RDColorPicker.xaml" /> and Style = "{DynamicResource ColorPickerButtonStyle}" to embed in the implementation part of the ColorPickerButton class, as in the class constructor;

public class ColorPickerButton:Button
{
   ....
   public ColorPickerButton()
   {
      ....
      //How to call resourcedictionary and apply style "ColorPickerButtonStyle" for this      button 
   }
}
+3
source share
1 answer

Sort of:

this.SetResourceReference(ColorPickerButton.StyleProperty, "ColorPickerButtonStyle");
+2
source

All Articles