[No0000124]WPF 扩展控件Behavior的几种方式
2021-06-19 13:06
标签:rac else red nsf cte sele change eof preview (1)定义Attached Dependency Property 使用上面定义好的Attached Dependency Property (1) 定义Behavior (2)使用Behavior [No0000124]WPF 扩展控件Behavior的几种方式 标签:rac else red nsf cte sele change eof preview 原文地址:https://www.cnblogs.com/lonelyxmas/p/10280142.html一、使用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));
}
}
TextBox Grid.Row="0" behaviors:DigitsOnlyBehavior.IsDigitOnly="True" Margin="6"/>
二、使用Behavior
public class DragBehavior : Behavior
Border Background="LightBlue" >
e:Interaction.Behaviors>
b:DragBehavior/>
e:Interaction.Behaviors>
TextBlock Text="Drag me around!" />
Border>
文章标题:[No0000124]WPF 扩展控件Behavior的几种方式
文章链接:http://soscw.com/essay/95968.html