Tommer
Tommer

Reputation: 29

How can I change the binding of the property Text with the EvenTrigger "GotFocus"

I am using a TextBox in WPF/XAML. I want to change the binding of the property Text with the event "GotFocus".

  1. TextBox has no focus (simplified code): <TextBox Text="{Binding ShortValue, RelativeSource={RelativeSource TemplatedParent}, Mode=TwoWay, UpdateSourceTrigger=LostFocus}"

  2. TextBox has focus: <TextBox Text="{Binding Value, RelativeSource={RelativeSource TemplatedParent}, Mode=TwoWay, UpdateSourceTrigger=LostFocus}"

Changing the binding of the property Text is to be created with XAML.

So far I have the following:

<TextBox>
   <i:Interaction.Triggers>
      <i:EventTrigger EventName="GotFocus">
           <!-- I'm at a loss here -->
      </i:EventTrigger>
   </i:Interaction.Triggers>
</TextBox>

Thanks.

Upvotes: 0

Views: 60

Answers (2)

mm8
mm8

Reputation: 169150

There is no behavior in the Microsoft.Xaml.Behaviors.Wpf package that lets you change the binding in pure XAML.

You could handle the event(s), either in the code-behind the view or in an attached behaviour, and create a new binding programmatically:

private void TextBox_GotFocus(object sender, RoutedEventArgs e) =>
    ((TextBox)sender).SetBinding(TextBox.TextProperty, new Binding("Value"));

private void TextBox_LostFocus(object sender, RoutedEventArgs e) =>
    ((TextBox)sender).SetBinding(TextBox.TextProperty, new Binding("ShortValue"));

XAML:

<TextBox 
    Text="{Binding ShortValue}"
    GotFocus="TextBox_GotFocus"
    LostFocus="TextBox_LostFocus"/>

Upvotes: 1

Muhammad Sulaiman
Muhammad Sulaiman

Reputation: 2605

Xaml-only solution

<TextBox>
    <TextBox.Style>
        <Style TargetType="{x:Type TextBox}"
               BasedOn="{StaticResource {x:Type TextBox}}">
            <Setter Property="Text" Value="{Binding ShortValue}" />
            <Style.Triggers>
                <Trigger Property="IsFocused" Value="True">
                    <Setter Property="Background" Value="Red" />
                    <Setter Property="Text" Value="{Binding Value}" />
                </Trigger>
            </Style.Triggers>
        </Style> 
    </TextBox.Style>
</TextBox>

Notice that you have to set the default binding (i.e ShortValue) inside the style..

Upvotes: 1

Related Questions