简体   繁体   中英

How to change textblock background when click textBlock in wpf?

I'm working on a Wpf project. And I want to change the background color of textBlock (textblockA) when I click on it. I have referenced this here article. But the problem is that I want to click on another textBlock (textBlockB) then textblockB changes color and textBlockA returns to the same color. (my english is a bit bad) Here is my Xaml code.

<UserControl x:Class="StandApp.Views.SettingView"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         xmlns:local="clr-namespace:StandApp.Views"
         mc:Ignorable="d" 
         d:DesignHeight="450" d:DesignWidth="800">
<UserControl.Resources>
    <Style TargetType="TextBlock">
        <Style.Triggers>
            <EventTrigger RoutedEvent="MouseDown">
                <BeginStoryboard>
                    <Storyboard>
                        <ColorAnimation Storyboard.TargetProperty="Background.Color" From="White" To="Yellow" Duration="0:0:0.1"></ColorAnimation>
                    </Storyboard>
                </BeginStoryboard>
            </EventTrigger>
        </Style.Triggers>
    </Style>
</UserControl.Resources>
<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="125*"/>
    </Grid.ColumnDefinitions>

    <Grid.RowDefinitions>
        <RowDefinition Height="60*"/>
    </Grid.RowDefinitions>

    <TextBlock Text="textBlockA" Background="White"></TextBlock>
    <TextBlock Text="textBlockB" Background="White"></TextBlock>
</Grid>
</UserControl>

I am a beginner to Wpf, hope everyone will help me. Thanks!

Up to My understanding when you click means when Focused on the text box then the background was supposed to be in red color

<Style x:Key="RedTextBoxStyle" TargetType="{x:Type TextBox}">
    <Style.Triggers>
        <Trigger Property="IsFocused" Value="true">
            <Setter Property="Background" Value="Red" />
        </Trigger>
    </Style.Triggers>
</Style>

<TextBox Style="{StaticResource RedTextBoxStyle}"  />

when you click textbox it will be Focused when IsFocused is true change Background to red

Note: TargetType="TextBlock" if you use like this. the style will be applied to to all the TextBlock of the scope so give it a key and use on the TextBox which is required of that style

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM