आपको अपने एप्लिकेशन में बक्सें के लिए डिफ़ॉल्ट शैली ओवरराइड कर सकते हैं। फिर इस शैली में, आप एक सेटर के साथ व्यवहार लागू करने के लिए कुछ दृष्टिकोण का उपयोग कर सकते हैं (आमतौर पर संलग्न गुणों का उपयोग करके)।
वह कुछ इस तरह होगा:
<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);
}
}
}
स्रोत
2012-11-21 17:04:46
ऑप्स, मैं शामिल किया था गलत व्यवहार अब फिक्स्ड! –
'TextBoxSelectAllOnFocusBehaviorExtension' क्या है – Peter