如何在CustomControl中以编程方式应用Style

时间:2011-06-16 03:41:12

标签: c# wpf xaml custom-controls styles

我在WPF中有一个自定义按钮,ColorPickerButton,并为它应用了样式“ColorPickerButtonStyle”,我必须像这样在xmal中应用;

<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" />

这个工作正常。但是如果我忘记应用样式“{DynamicResource ColorPickerButtonStyle}”那么按钮看起来就像死鱼。 我在这里要做的是,我想应用这部分&lt; ResourceDictionary Source =“RDColorPicker.xaml”/&gt;和Style =“{DynamicResource ColorPickerButtonStyle}”将嵌入ColorPickerButton类的实现部分,就像在Class的构造函数中一样;

public class ColorPickerButton:Button
{
   ....
   public ColorPickerButton()
   {
      ....
      //How to call resourcedictionary and apply style "ColorPickerButtonStyle" for this      button 
   }
}

1 个答案:

答案 0 :(得分:2)

类似的东西:

this.SetResourceReference(ColorPickerButton.StyleProperty, "ColorPickerButtonStyle");