WPF通过附加属性在ViewModel中操作IsFocused属性

话不多说,直接贴代码

1.首先新建一个类

 1 namespace Ycims.AppClient.Common
 2 {
 3     public static class FocusExtension
 4     {
 5         public static readonly DependencyProperty IsFocusedProperty =
 6             DependencyProperty.RegisterAttached("IsFocused", typeof(bool?), typeof(FocusExtension), new FrameworkPropertyMetadata(IsFocusedChanged) { BindsTwoWayByDefault = true });
 7 
 8         public static bool? GetIsFocused(DependencyObject element)
 9         {
10             if (element == null)
11             {
12                 throw new ArgumentNullException("element");
13             }
14 
15             return (bool?)element.GetValue(IsFocusedProperty);
16         }
17 
18         public static void SetIsFocused(DependencyObject element, bool? value)
19         {
20             if (element == null)
21             {
22                 throw new ArgumentNullException("element");
23             }
24 
25             element.SetValue(IsFocusedProperty, value);
26         }
27 
28         private static void IsFocusedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
29         {
30             var fe = (FrameworkElement)d;
31 
32             if (e.OldValue == null)
33             {
34                 fe.GotFocus += FrameworkElement_GotFocus;
35                 fe.LostFocus += FrameworkElement_LostFocus;
36             }
37 
38             if (!fe.IsVisible)
39             {
40                 fe.IsVisibleChanged += new DependencyPropertyChangedEventHandler(fe_IsVisibleChanged);
41             }
42 
43             if (e.NewValue != null && (bool)e.NewValue)
44             {
45                 fe.Focus();
46             }
47         }
48 
49         private static void fe_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
50         {
51             var fe = (FrameworkElement)sender;
52             if (fe.IsVisible && (bool)fe.GetValue(IsFocusedProperty))
53             {
54                 fe.IsVisibleChanged -= fe_IsVisibleChanged;
55                 fe.Focus();
56             }
57         }
58 
59         private static void FrameworkElement_GotFocus(object sender, RoutedEventArgs e)
60         {
61             ((FrameworkElement)sender).SetValue(IsFocusedProperty, true);
62         }
63 
64         private static void FrameworkElement_LostFocus(object sender, RoutedEventArgs e)
65         {
66             ((FrameworkElement)sender).SetValue(IsFocusedProperty, false);
67         }
68     }
69 }
FocusExtension.cs

 

 2.在xmal中引入这个类的命名空间

xmlns:conv="clr-namespace:Ycims.AppClient.Common"

 

3.在需要绑定的控件中绑定变量

<TextBox x:Name="AAA" conv:FocusExtension.IsFocused="{Binding IsAAAFocus}"  Text="{Binding Path=AAA}" ></TextBox>

 

4.在viewModel中修改<IsAAAFocus>这个为true就可以绑定焦点了

posted @ 2022-07-29 16:28  -萌大宝  阅读(208)  评论(0编辑  收藏  举报