2012-11-21 21 views
6

में सभी टेक्स्टबॉक्सों के व्यवहार को संलग्न करें क्या सिल्वरलाइट एप्लिकेशन में सभी टेक्स्टबॉक्स में व्यवहार संलग्न करना संभव है?सिल्वरलाइट

मुझे सभी टेक्स्ट बॉक्स में सरल कार्यक्षमता जोड़ने की आवश्यकता है। (फोकस घटना पर सभी पाठ का चयन करें)

void Target_GotFocus(object sender, System.Windows.RoutedEventArgs e) 
    { 
     Target.SelectAll(); 
    } 

उत्तर

8

आपको अपने एप्लिकेशन में बक्सें के लिए डिफ़ॉल्ट शैली ओवरराइड कर सकते हैं। फिर इस शैली में, आप एक सेटर के साथ व्यवहार लागू करने के लिए कुछ दृष्टिकोण का उपयोग कर सकते हैं (आमतौर पर संलग्न गुणों का उपयोग करके)।

वह कुछ इस तरह होगा:

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

व्यवहार कार्यान्वयन:

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(); 
    } 
} 

और हमें व्यवहार लागू मदद से जुड़ी संपत्ति:

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