对于DataTemplate中的派生控件,将忽略显式样式

时间:2016-02-25 16:47:34

标签: .net wpf xaml

有些款式在这里没有按预期工作。这是演示风格,它使背景为橙色,以证明它已应用于控件:

<Style x:Key="OrangeTestStyle" TargetType="TextBox">
    <Setter Property="Background" Value="Orange"/>
</Style>

我通常可以像TextBox一样使用它,也可以使用从TextBox派生的我自己的类:

<TextBox Style="{StaticResource OrangeTestStyle}"/><!-- orange -->
<ui:UnitTextBox Style="{StaticResource OrangeTestStyle}"/><!-- orange -->

两者都有橙色背景。但如果它在DataTemplate中,它不适用于派生控件。实际上,根本没有明确设置样式应用于任何派生控件。标准框架控件工作得很好:

<DataTemplate>
    <StackPanel>
        <TextBox Style="{StaticResource OrangeTestStyle}"/><!-- orange -->
        <ui:UnitTextBox Style="{StaticResource OrangeTestStyle}"/><!-- white -->
    </StackPanel>
</DataTemplate>

我的派生控件不会覆盖与Style相关的任何内容。它只是添加了一个新的依赖属性,并在其他视觉元素中显示其内容,这是一种装饰。但它仍然直接来自TextBox。样式也可以在派生控件中使用,但如果在模板中则不行。样式也适用于模板,但不适用于派生控件。 (我的应用程序中有其他派生控件。)

这里的问题是什么?

.NET 4.0,Visual Studio 2010,Windows 7。

1 个答案:

答案 0 :(得分:1)

SetResourceReference(StyleProperty, typeof(TextBox))构造函数中删除UnitTextBox应该修复它。

相关问题