WPF 使用行为<Behavior>实现SAP焦点样式
作者:互联网
效果
首先添加引用 System.Windows.Interactivity.WPF (需要用nuget包下载)
准备一个行为类 继承Behavior类
1 /// <summary> 2 /// 控件获取焦点后的行为 3 /// </summary> 4 public class FocusBehavior : Behavior<FrameworkElement> 5 { 6 protected override void OnAttached() 7 { 8 base.OnAttached(); 9 AssociatedObject.GotFocus += AssociatedObject_GotFocus;//获取焦点的事件 10 AssociatedObject.LostFocus += AssociatedObject_LostFocus;//失去焦点的时间 11 } 12 13 protected override void OnDetaching() 14 { 15 base.OnDetaching(); 16 AssociatedObject.GotFocus -= AssociatedObject_GotFocus;//移除 17 AssociatedObject.LostFocus -= AssociatedObject_LostFocus;//移除 18 } 19 20 private void AssociatedObject_GotFocus(object sender, RoutedEventArgs e) 21 { 22 var control = sender as FrameworkElement; 23 var layer = AdornerLayer.GetAdornerLayer(control); 24 layer.Add(new CornerAdorner(control));//这里就用以前实现的装饰器类 25 } 26 27 private void AssociatedObject_LostFocus(object sender, RoutedEventArgs e) 28 { 29 var control = sender as FrameworkElement; 30 var layer = AdornerLayer.GetAdornerLayer(control); 31 var adorners = layer.GetAdorners(control); 32 if (adorners != null) 33 { 34 for (int i = adorners.Length - 1; i >= 0; i--) 35 { 36 layer.Remove(adorners[i]); 37 } 38 } 39 } 40 }
界面引用命名空间
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
界面内容
1 <Grid> 2 <StackPanel 3 x:Name="stackPanel" 4 HorizontalAlignment="Center" 5 VerticalAlignment="Center" 6 Orientation="Vertical"> 7 <TextBox Width="200" Margin="15"> 8 <i:Interaction.Behaviors> 9 <local:FocusBehavior /> 10 </i:Interaction.Behaviors> 11 </TextBox> 12 <CheckBox Margin="15" Content="点击"> 13 <i:Interaction.Behaviors> 14 <local:FocusBehavior /> 15 </i:Interaction.Behaviors> 16 </CheckBox> 17 <TextBox Width="200" Margin="15" /> 18 <TextBox Width="200" Margin="15" /> 19 <Button Margin="15" Content="确定"> 20 <i:Interaction.Behaviors> 21 <local:FocusBehavior /> 22 </i:Interaction.Behaviors> 23 </Button> 24 25 <TextBlock 26 Width="200" 27 Margin="15" 28 HorizontalAlignment="Center" 29 Text="边框测试"> 30 <i:Interaction.Behaviors> 31 <local:FocusBehavior /> 32 </i:Interaction.Behaviors> 33 </TextBlock> 34 </StackPanel> 35 </Grid>
标签:control,layer,LostFocus,样式,AssociatedObject,GotFocus,var,WPF,SAP 来源: https://www.cnblogs.com/AtTheMoment/p/14960832.html