1
votes

I have two questions here:

1.

Lets look at the xaml below:

<Style TargetType="TextBlock">
    <Style.Triggers>
        <EventTrigger RoutedEvent="MouseDown">
            <EventTrigger.Actions>
                <BeginStoryboard>
                    <Storyboard>
                        <ColorAnimation Storyboard.TargetProperty="Background.Color" To="LightBlue" Duration="0:0:0.100" />
                    </Storyboard>
                </BeginStoryboard>
            </EventTrigger.Actions>
        </EventTrigger>
    </Style.Triggers>
</Style>

<TextBlock Text="123" />
<TextBlock Text="abc" />

Current behavior of the above code:

When I click on the textblock with text = 123, its background is changed to LightBlue. Now if I click on the textblock with text = abc, its background is changed to LightBlue. But the background of textblock with text = 123 remains LightBlue.

Requirements:

I want to change the background of textblock with text = 123 to Transparent when I click on the textBlock with text = abc.

What changes should I make to the above xaml to get the required functionality?

2.

How to set TargetType of a same Style for multiple elements.

Lets say,

I want to use the style mentioned in the above code for TextBox also, then How can I use it without repeating code and also without using x:Key attribute?

2

2 Answers

2
votes

For the first question: I think this would be easy to implement from code-behind, by using the event GotFocus, which is the event fired when you click on a textbox by either keyboard, mouse etc...

For the second question: You can set the target Type of multiple different controls, by setting the TargetType to their parent class, for example TargetType="{x:Type Control}"

For more information (Almost the same case scenario), please check:

Can you define multiple TargetTypes for one XAML style?

1
votes

Though Nirvana Priest has answered second question .the answer for first question is Write the same trigger for LostFocus like

<Style TargetType="TextBlock">
        <Style.Triggers>
            <EventTrigger RoutedEvent="MouseDown">
                <EventTrigger.Actions>
                    <BeginStoryboard>
                        <Storyboard>
                            <ColorAnimation Storyboard.TargetProperty="Background.Color" To="LightBlue" Duration="0:0:0.100" />
                        </Storyboard>
                    </BeginStoryboard>
                </EventTrigger.Actions>
            </EventTrigger>
            <EventTrigger RoutedEvent="LostFocus">
                <EventTrigger.Actions>
                    <BeginStoryboard>
                        <Storyboard>
                            <ColorAnimation Storyboard.TargetProperty="Background.Color" To="White" Duration="0:0:0.100" />
                        </Storyboard>
                    </BeginStoryboard>
                </EventTrigger.Actions>
            </EventTrigger>
        </Style.Triggers>
     </Style>

I hope this will help.