2012-11-21 7 views

答えて

8

あなたはあなたのアプリケーション内のTextBoxのデフォルトのスタイルを上書きすることができます(フォーカスイベントのすべてのテキストを選択します)。次に、このスタイルでは、セッターでビヘイビアを適用するためのアプローチを使用できます(一般にはアタッチされたプロパティを使用します)。

それは考え、このような何か:私たちは行動適用を支援する

public class TextBoxSelectAllOnFocusBehavior : Behavior<TextBox> 
{ 
    protected override void OnAttached() 
    { 
     base.OnAttached(); 

     this.AssociatedObject.GotMouseCapture += this.OnGotFocus; 
     this.AssociatedObject.GotKeyboardFocus += this.OnGotFocus; 
    } 

    protected override void OnDetaching() 
    { 
     base.OnDetaching(); 

     this.AssociatedObject.GotMouseCapture -= this.OnGotFocus; 
     this.AssociatedObject.GotKeyboardFocus -= this.OnGotFocus; 
    } 

    public void OnGotFocus(object sender, EventArgs args) 
    { 
     this.AssociatedObject.SelectAll(); 
    } 
} 

そして添付プロパティ:

<Application.Resources> 
    <Style TargetType="TextBox"> 
     <Setter Property="local:TextBoxEx.SelectAllOnFocus" Value="True"/> 
    </Style> 
</Application.Resources> 

行動実装

public static class TextBoxEx 
{ 
    public static bool GetSelectAllOnFocus(DependencyObject obj) 
    { 
     return (bool)obj.GetValue(SelectAllOnFocusProperty); 
    } 
    public static void SetSelectAllOnFocus(DependencyObject obj, bool value) 
    { 
     obj.SetValue(SelectAllOnFocusProperty, value); 
    } 
    public static readonly DependencyProperty SelectAllOnFocusProperty = 
     DependencyProperty.RegisterAttached("SelectAllOnFocus", typeof(bool), typeof(TextBoxSelectAllOnFocusBehaviorExtension), new PropertyMetadata(false, OnSelectAllOnFocusChanged)); 


    private static void OnSelectAllOnFocusChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args) 
    { 
     var behaviors = Interaction.GetBehaviors(sender); 

     // Remove the existing behavior instances 
     foreach (var old in behaviors.OfType<TextBoxSelectAllOnFocusBehavior>().ToArray()) 
      behaviors.Remove(old); 

     if ((bool)args.NewValue) 
     { 
      // Creates a new behavior and attaches to the target 
      var behavior = new TextBoxSelectAllOnFocusBehavior(); 

      // Apply the behavior 
      behaviors.Add(behavior); 
     } 
    } 
} 
+0

オプスを、私は含まれていました間違った行動。今すぐ修正! –

+0

'TextBoxSelectAllOnFocusBehaviorExtension'とは何ですか? – Peter

関連する問題