[No0000124]WPF 扩展控件Behavior的几种方式
一、使用Attached Dependency Property的方式
(1)定义Attached Dependency Property
public static class DigitsOnlyBehavior { public static bool GetIsDigitOnly(DependencyObject obj) { return (bool)obj.GetValue(IsDigitOnlyProperty); } public static void SetIsDigitOnly(DependencyObject obj, bool value) { obj.SetValue(IsDigitOnlyProperty, value); } public static readonly DependencyProperty IsDigitOnlyProperty = DependencyProperty.RegisterAttached("IsDigitOnly", typeof(bool), typeof(DigitsOnlyBehavior), new PropertyMetadata(false, OnIsDigitOnlyChanged)); private static void OnIsDigitOnlyChanged(object sender, DependencyPropertyChangedEventArgs e) { // ignoring error checking var textBox = (TextBox)sender; var isDigitOnly = (bool)(e.NewValue); if (isDigitOnly) textBox.PreviewTextInput += BlockNonDigitCharacters; else textBox.PreviewTextInput -= BlockNonDigitCharacters; } private static void BlockNonDigitCharacters(object sender, TextCompositionEventArgs e) { e.Handled = e.Text.Any(ch => !Char.IsDigit(ch)); } }
使用上面定义好的Attached Dependency Property
<TextBox Grid.Row="0" behaviors:DigitsOnlyBehavior.IsDigitOnly="True" Margin="6"/>
二、使用Behavior<T>
(1) 定义Behavior
public class DragBehavior : Behavior<UIElement> { private Point elementStartPosition; private Point mouseStartPosition; private TranslateTransform transform = new TranslateTransform(); protected override void OnAttached() { Window parent = Application.Current.MainWindow; AssociatedObject.RenderTransform = transform; AssociatedObject.MouseLeftButtonDown += (sender, e) => { elementStartPosition = AssociatedObject.TranslatePoint( new Point(), parent ); mouseStartPosition = e.GetPosition(parent); AssociatedObject.CaptureMouse(); }; AssociatedObject.MouseLeftButtonUp += (sender, e) => { AssociatedObject.ReleaseMouseCapture(); }; AssociatedObject.MouseMove += (sender, e) => { Vector diff = e.GetPosition( parent ) - mouseStartPosition; if (AssociatedObject.IsMouseCaptured) { transform.X = diff.X; transform.Y = diff.Y; } }; } }
(2)使用Behavior
<Border Background="LightBlue" > <e:Interaction.Behaviors> <b:DragBehavior/> </e:Interaction.Behaviors> <TextBlock Text="Drag me around!" /> </Border>
摘抄自网络,便于检索查找。