Repository navigation
Expand file tree
/
Copy pathMainWindow.xaml.cs
More file actions
94 lines (84 loc) · 3.23 KB
/
Copy pathMainWindow.xaml.cs
File metadata and controls
94 lines (84 loc) · 3.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace PlanNotes
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
PreviewMouseDown += Window_PreviewMouseDown;
Loaded += MainWindow_Loaded;
}
private void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
// 递归找所有 Button 并绑定
BindButtonsToLostFocus(this); // 从当前 Window 开始遍历
}
// 🔥 递归方法:遍历 VisualTree,找 Button 加 Click handler
private void BindButtonsToLostFocus(DependencyObject parent)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
{
var child = VisualTreeHelper.GetChild(parent, i);
if (child is Button button)
{
// 绑定统一 handler(如果已有 Click,先移除再加,避免叠加)
button.Click -= GlobalButtonLostFocus_Click; // 防重复
button.Click += GlobalButtonLostFocus_Click; // 加失焦 handler
}
// 递归子元素(支持嵌套如 StackPanel 内按钮)
BindButtonsToLostFocus(child);
}
}
// 🔥 统一 Click handler:业务 + 自动失焦
private void GlobalButtonLostFocus_Click(object sender, RoutedEventArgs e)
{
// 🔥 原有业务逻辑:放这儿,或用 if (sender is Button btn) { /* btn 特定逻辑 */ }
// 示例:MessageBox.Show("按钮点击了!😊");
// 🔥 核心:点击后强制失焦,杀黑框
Keyboard.ClearFocus(); // 全局清焦点,瞬间无黑框
// 可选:焦点回窗口,避免“空焦点”感
// this.Focus();
}
private void Window_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
var element = Keyboard.FocusedElement as FrameworkElement;
if (element is TextBox focusedTextBox)
{
var clickedElement = Mouse.DirectlyOver as DependencyObject;
if (!IsChildOf(clickedElement, focusedTextBox))
{
var scope = FocusManager.GetFocusScope(this);
FocusManager.SetFocusedElement(scope, this); // 将焦点给窗口本身
Keyboard.ClearFocus();
}
}
}
private bool IsChildOf(DependencyObject child, DependencyObject parent)
{
while (child != null)
{
if (child == parent)
return true;
child = VisualTreeHelper.GetParent(child);
}
return false;
}
private void close_Click(object sender, RoutedEventArgs e)
{
Close();
}
}
}