Function call within XAML code?

18,954

You can do this using attached behaviours.

Example

public static class TextBoxBehaviour
{
    public static bool GetSelectAll(TextBoxBase target)
    {
        return (bool)target.GetValue(SelectAllAttachedProperty);
    }

    public static void SetSelectAll(TextBoxBase target, bool value)
    {
        target.SetValue(SelectAllAttachedProperty, value);
    }

    public static readonly DependencyProperty SelectAllAttachedProperty = DependencyProperty.RegisterAttached("SelectAll", typeof(bool), typeof(TextBoxBehaviour), new UIPropertyMetadata(false, OnSelectAllAttachedPropertyChanged));

    static void OnSelectAllAttachedPropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
    {
        ((TextBoxBase)o).SelectAll();
    }
}

Usage

<Style TargetType="{x:Type TextBox}" xmlns:behaviours="clr-namespace:Controls.Behaviours">
  <Style.Triggers>
      <Trigger Property="IsKeyboardFocusWithin" Value="True">
          <Setter Property="Background" Value="#FFFFD1D9"/>
          <Setter Property="behaviours:TextBoxBehaviour.SelectAll" Value="True"/>
     </Trigger>
  </Style.Triggers>
</Style>

References

NB: Wasn't able to test the above implementation, in theory though it should just work™.

HTH,

Share:
18,954
Matt H.
Author by

Matt H.

Updated on June 04, 2022

Comments

  • Matt H.
    Matt H. almost 2 years

    I'd like to set a style on all my TextBox controls that does the following when it receives keyboard focus:

    1) Change the background color
    2) Call .SelectAll() to highlight all text

    I have this so far:

    <Style TargetType="TextBox">
    <Style.Triggers>
                <Trigger Property="IsKeyboardFocusWithin" Value="True">
                    <Setter Property="Background">
                        <Setter.Value>
                            <SolidColorBrush Color="#FFFFD1D9"/>
                        </Setter.Value>
                    </Setter>
               </Trigger>
    </Style.Triggers>
    </Style>
    

    Is there a way to also call .SelectAll() ? Thanks.

  • Ray Burns
    Ray Burns almost 14 years
    +1 Excellent answer. Almost exactly what I would have written. Personally I would change the body of the method to simply ((TextBoxBase)target).SelectAll() so as to throw an intelligible exception if the property is used erroneously. From a QA perspective this is better in the long run than silently ignoring such errors: You catch your bugs up front rather than having them lurk hidden for years.
  • Dennis
    Dennis almost 14 years
    @Ray Burns: I agree. It is a bad habit that I am trying to move away from. I have edited my answer.
  • BCA
    BCA about 10 years
    Thanks for that--it worked perfectly. FYI, for anyone who wishes to implement this for a PasswordBox: implement a separate PasswordBoxBehaviour class and replace all occurrences of TextBoxBase with PasswordBox.