c# - 如何在 CustomControl 中以编程方式应用样式

标签 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}”,那么按钮将看起来像死鱼。 我想在这里做的是,我想将这部分 和 Style="{DynamicResource ColorPickerButtonStyle}"嵌入到 ColorPickerButton 类的实现部分,就像在构造函数中一样类;

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

最佳答案

类似于:

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

关于c# - 如何在 CustomControl 中以编程方式应用样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6366851/

相关文章:

c# - 如何使用反射根据xml文件中的文本实例化一个新类

c# - 具有名为 "Item"的索引器和属性的类

.net - 在 WPF 或 winform 中绘制 3D 图形

visual-studio-2010 - Visual Studio 自定义 XAML 设计器

wpf - XAML - 如何在 StackPanel 中将控件彼此对齐

c# - 从任务栏删除 XAML 窗口

C# 将 dd/MMMM/yyyy 转换为 yyyymmdd(俄语)

c# - 无法从 Web 服务连接到 MS 访问数据库

c# - 将 contextMenu 绑定(bind)到与 TreeView 不同的 View 模型

c# - 只读指定span