Search code examples
wpfxamltextbox

WPF - Triggers on TextBox click


I'm trying to write a xaml piece that will set my TextBox's text whenever it gets / loses focus. Currently it looks like this :

<TextBox Name="TextBoxLogin" HorizontalAlignment="Left" Height="25" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="160">
                <TextBox.Style>
                    <Style TargetType="TextBox">
                        <Style.Triggers>
                            <Trigger Property="IsMouseCaptured" Value="True">
                                <Setter Property="Text" Value="test"/>
                            </Trigger>
                        </Style.Triggers>
                    </Style>
                </TextBox.Style>
            </TextBox>

But for some reason whenever I click it, the text doesn't change. I'd like to know why and what are my options to make it work. I also tried other properties like IsStylusCaptured and IsFocused, they didn't work either.


Solution

  • The issue is simple, you are setting the Text property in the first line :( Either set it in the STyle or don't set it :

     <TextBox Name="TextBoxLogin" HorizontalAlignment="Left" Height="25" TextWrapping="Wrap" VerticalAlignment="Top" Width="160">
                <TextBox.Style>
                    <Style TargetType="TextBox">
                    <Setter Property="Text" Value = "TextHEre"/>
                        <Style.Triggers>
                            <Trigger Property="IsMouseCaptured" Value="True">
                                <Setter Property="Text" Value="test"/>
                            </Trigger>
                        </Style.Triggers>
                    </Style>
                </TextBox.Style>
      </TextBox>