【问题标题】:Custom control not inheriting parent's styles自定义控件不继承父样式
【发布时间】:2016-10-11 18:52:35
【问题描述】:

我试图在我的 WPF 应用程序中保持跨元素的统一外观,同时我想创建一个修改后的TextBox。但是,当我这样做时,我在应用程序级别为 TextBox 定义的样式不会应用于我创建的类,即使为我的自定义控件创建的样式使用的是 BasedOn 属性。

是否有什么我遗漏的东西导致它的行为与我预期的不同?

我用这个设置在 VS2010 的一个全新的 WPF 项目中重现了这个问题:

C#代码:

public class CustomTextBox : TextBox
{
    static CustomTextBox() {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomTextBox), new FrameworkPropertyMetadata(typeof(CustomTextBox)));
    }
}

Themes\Generic.xaml 中的 XAML:

<Style TargetType="{x:Type local:CustomTextBox}" BasedOn="{StaticResource {x:Type TextBox}}"/>

App.xaml 中的 XAML:

<Application.Resources>
    <Style TargetType="TextBox">
        <Setter Property="Background" Value="Red"/>
    </Style>
</Application.Resources>

但是,在设计器中以及当我运行应用程序时,CustomTextBox 会退回到文本框的默认样式而不是红色背景,即使 the documentation for the BasedOn property 建议我的派生类应该具有这种样式。 ..

有几种方法可以扩展或继承 WPF 中的样式。样式可以通过此属性基于其他样式。使用此属性时,新样式将继承未在新样式中明确重新定义的原始样式的值。

...

注意:如果您创建具有 TargetType 属性的样式并将其基于另一个也定义了 TargetType 属性的样式,则派生样式的目标类型必须与或派生自基本样式的类型。

【问题讨论】:

    标签: wpf xaml .net-4.0 custom-controls


    【解决方案1】:

    简短回答:您的样式基于静态资源

    <Style TargetType="{x:Type local:CustomTextBox}" BasedOn="{StaticResource {x:Type TextBox}}"/>
    

    当你这样做时,你并没有改变 StaticResource

    <Style TargetType="TextBox">
        <Setter Property="Background" Value="Red"/>
    </Style>
    

    所以 CustomTextBox 不应该继承红色背景。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多