6
是否可以將行爲附加到Silverlight應用程序中的所有文本框?將行爲附加到Silverlight中的所有文本框
我需要爲所有文本框添加簡單的功能。 (選擇對焦點事件的所有文字)
void Target_GotFocus(object sender, System.Windows.RoutedEventArgs e)
{
Target.SelectAll();
}
是否可以將行爲附加到Silverlight應用程序中的所有文本框?將行爲附加到Silverlight中的所有文本框
我需要爲所有文本框添加簡單的功能。 (選擇對焦點事件的所有文字)
void Target_GotFocus(object sender, System.Windows.RoutedEventArgs e)
{
Target.SelectAll();
}
您可以覆蓋的默認樣式在您的應用程序文本框。然後以這種風格,你可以使用一些方法來使用setter來應用行爲(通常使用附加屬性)。
這將是這樣的:
<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);
}
}
}
行動,我已經列入錯誤的行爲。現在修好! –
什麼是「TextBoxSelectAllOnFocusBehaviorExtension」 – Peter