Stopbyte

How to set a Boolean value in an EventTrigger with Setter in WPF?

I’ve created a Button and a TextBox in WPF, and I want when the button is clicked to trigger the change of the TextBox Boolean Property value, in this case it’s Focusable. without any code behind.

here is an example:

<ControlTemplate.Triggers>
  <EventTrigger SourceName="MyButton" RoutedEvent="Button.Click">
    <Setter TargetName="MyTextBox" Property="Focusable" Value="False" />
  </EventTrigger>

Here is a sample that sets and clears Focusable on a TextBox from an EventTrigger.
Hopefully you can adapt this example to your situation.

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition/>
        <RowDefinition/>
        <RowDefinition/>
    </Grid.RowDefinitions>
    <TextBox 
        x:Name="tb"
        Grid.Row="0"
        Text="Here is some sample text">
    </TextBox>
    <Button 
        x:Name="btnFocusTrue"
        Grid.Row="1"
        Content="Set True">
    </Button>
    <Button 
        x:Name="btnFocusFalse"
        Grid.Row="2"
        Content="Set False">
    </Button>
    <Grid.Triggers>
        <EventTrigger RoutedEvent="Button.Click" SourceName="btnFocusTrue">
            <BeginStoryboard Name="FoucsTrueStoryboard">
                <Storyboard >
                    <BooleanAnimationUsingKeyFrames
                        Storyboard.TargetName="tb"
                        Storyboard.TargetProperty="(TextBox.Focusable)">
                        <DiscreteBooleanKeyFrame
                            KeyTime="00:00:01"
                            Value="True" />
                    </BooleanAnimationUsingKeyFrames>
                </Storyboard>
            </BeginStoryboard>
        </EventTrigger>
        <EventTrigger RoutedEvent="Button.Click" SourceName="btnFocusFalse">
            <BeginStoryboard Name="FoucsFalseStoryboard">
                <Storyboard >
                    <BooleanAnimationUsingKeyFrames
                        Storyboard.TargetName="tb"
                        Storyboard.TargetProperty="(TextBox.Focusable)">
                        <DiscreteBooleanKeyFrame
                            KeyTime="00:00:01"
                            Value="False" />
                    </BooleanAnimationUsingKeyFrames>
                </Storyboard>
            </BeginStoryboard>
        </EventTrigger>
    </Grid.Triggers>
</Grid>
1 Like

KeyTime can be 00:00:0.1 or 00:00:00 will react faster.

1 Like

@jms Yep; true, 0.5s would be better, as 00:00:00 will not let us see the transition, and i used an EventTrigger in the first place to allow seeing some nice animation.
thanks for your comment it really makes sense though.

1 Like