Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
854 views
in Technique[技术] by (71.8m points)

wpf - Function call within XAML code?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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,


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...