Styling both Hyperlink and TextBlock with one style?

I have two types of text that should follow similar enumeration-based coloring rules:

 public enum Modes
 {
   A,
   B,
   C
 }

For coloring, a style with DataTriggermarkup is used:

      <Style TargetType="SEE BELOW" x:Key="Coloring">
            <Style.Triggers>
                <DataTrigger Binding="{Binding Path=.}" Value="A">
                    <Setter Property="Foreground" Value="Red" />
                </DataTrigger>
                <DataTrigger Binding="{Binding Path=.}" Value="B">
                    <Setter Property="Foreground" Value="Green" />
                </DataTrigger>
               <DataTrigger Binding="{Binding Path=.}" Value="C">
                    <Setter Property="Foreground" Value="Blue" />
                </DataTrigger>
            </Style.Triggers>
        </Style>

One use case is System.Windows.Documents.Hyperlinkwith a nested one System.Windows.Controls.TextBlock:

<Hyperlink><TextBlock/></Hyperlink>

and the other is just TextBlock:

<TextBlock Style="{StaticResource Coloring}" Text="yada"/>

I can of course style both elements TextBlock:

<TextBlock Style="{StaticResource Coloring}" Text="yada"/>
<Hyperlink><TextBlock Style="{StaticResource Coloring}"/></Hyperlink>

but it doesn’t allow styling the Hyperlink case underline.

If I try to create a style for both types:

<TextBlock Style="{StaticResource Coloring}" Text="yada"/>
<Hyperlink Style="{StaticResource Coloring}"><TextBlock/></Hyperlink>

Then the stylization fails, as there is (apparently) no general type of ancestor to use in the TargetTypestyle attribute .

, , , , XAML, . , ( Hyperlink TextBlock), .

... : XAML ?

+3
2

Hyperlinks , TextBlocks, , :

<Style TargetType="TextBlock" x:Key="Coloring">
        <Style.Resources>
            <Style TargetType="Hyperlink">
                <Setter Property="Foreground" Value="{Binding Foreground,RelativeSource={RelativeSource FindAncestor,AncestorType=TextBlock}}"/>
            </Style>
        </Style.Resources>
            <Setter Property="Foreground" Value="Orange"/>
        <Style.Triggers>
        <DataTrigger Binding="{Binding Path=.}" Value="A">
            <Setter Property="Foreground" Value="Red" />
        </DataTrigger>
        <DataTrigger Binding="{Binding Path=.}" Value="B">
            <Setter Property="Foreground" Value="Green" />
        </DataTrigger>
        <DataTrigger Binding="{Binding Path=.}" Value="C">
            <Setter Property="Foreground" Value="Blue" />
        </DataTrigger>
    </Style.Triggers>
</Style>

, , .

+6

. TextBlock. TextBlock:

<TextBlock Style="{StaticResource Coloring}"><Hyperlink><TextBlock/></HyperLink></TextBlock>

TextBlock. ( )

0

Source: https://habr.com/ru/post/1732431/


All Articles