水印字体/家庭

时间:2013-11-07 17:56:30

标签: c# wpf xaml attached-properties adorner

我目前正在创建一个带有水印文本的TextBox,并且有一些样式问题。 为了创建水印本身,我已经包含了这里解释的代码 Watermark / hint text / placeholder TextBox in WPF 我没有使用接受的答案,而是使用票数最高的答案。 (使用Adorner的那个)

我的textblock看起来像这样:

<AdornerDecorator>
    <TextBox HorizontalAlignment="Right"
                VerticalAlignment="Center"
                Width="190"
                Padding="16,2,20,2">
        <utils:WatermarkService.Watermark>
            <TextBlock Text="Search" />
        </utils:WatermarkService.Watermark>
    </TextBox>
</AdornerDecorator>

现在我面临的问题是,使用这个附加属性,其中的文本块超出了我在app.xaml中声明的样式范围。 样式看起来像这样:

<Style TargetType="{x:Type Window}">
    <Setter Property="FontFamily"
            Value="Tahoma" />
    <Setter Property="FontSize"
            Value="8pt"></Setter>
    <Setter Property="Background"
            Value="{DynamicResource {x:Static SystemColors.ControlLightBrushKey}}" />
</Style>

如何在app.xaml中的附加属性中设置文本块的样式,最好是基于这种样式,所以我不必声明serval时间。

1 个答案:

答案 0 :(得分:1)

Declare same style for TextBlock以及in Application resources。这样,它将应用于应用程序中的所有TextBlock,无论它们是Adorners还是窗口的一部分。

<Style TargetType="{x:Type TextBlock}">
   <Setter Property="FontFamily"
           Value="Tahoma" />
   <Setter Property="FontSize"
           Value="8pt"></Setter>
   <Setter Property="Background"
         Value="{DynamicResource {x:Static SystemColors.ControlLightBrushKey}}"/>
</Style>

<强>更新

如果您不想复制资源,最好使用Label代替TextBlock。这样,您就可以在Control上应用样式,并可以从中派生出WindowLabel的样式。

但这不适用于TextBlock,因为它不是来自Control

   <Style TargetType="Control" x:Key="BaseStyle">
        <Setter Property="FontFamily" Value="Tahoma" />
        <Setter Property="FontSize" Value="8pt"></Setter>
        <Setter Property="Background" 
        Value="{DynamicResource {x:Static SystemColors.ControlLightBrushKey}}"/>
    </Style>

    <Style TargetType="{x:Type Window}"
           BasedOn="{StaticResource BaseStyle}"/>
    <Style TargetType="{x:Type Label}"
           BasedOn="{StaticResource BaseStyle}"/>

然后,如果您在AdornerDecorator中使用Label代替TextBlock,它将正常工作。