Search code examples
c#wpfxamlattached-propertiesadorner

Watermark fontsize/family


I am currently creating a TextBox with a watermark text and have a little styling problem. To create the Watermark itself I have included the code explained in here Watermark / hint text / placeholder TextBox in WPF I did not use the accepted answer, but the one with the highest votes. (the one using Adorner)

My textblock looks like this:

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

Now I face the problem that with this attached property, the textblock in it gets out of scope from my styling I have declared in app.xaml. The styling looks like this:

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

How is it possible to style the textblock within the attached property in app.xaml, preferable with basedon this style so I dont have to declare it serval times.


Solution

  • Declare same style for TextBlock as well in Application resources. This way it will be applied to all TextBlocks in your application no matter whether they are part of Adorners or window.

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

    UPDATE

    If you don't want to duplicate resources, best you can get is use Label instead of TextBlock. That way you can have style applied on Control and can derive styles for Window and Label from that.

    But this won't work for TextBlock since it doesn't derive from 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}"/>
    

    Then if you use Label inside AdornerDecorator in place of TextBlock, it will work fine.