CongSyIT
CongSyIT

Reputation: 61

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!

Upvotes: 0

Views: 696

Answers (1)

Avinash Reddy
Avinash Reddy

Reputation: 937

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

Upvotes: 1

Related Questions