WPF Loading 加载遮罩组件:优雅的全局加载动画

WPF 做异步操作(网络请求、文件读写)时,通常需要给用户一个"正在处理"的反馈。原生 WPF 没有现成的 Loading 组件,很多人要么不处理,要么自己画一个转圈动画。

本文分享一个纯 C# 代码实现的 Loading 遮罩组件,会覆盖整个窗口区域,阻止用户重复操作,并显示旋转加载动画和提示文字。

效果预览

  • 半透明黑色遮罩覆盖整个窗口,阻止鼠标穿透
  • 居中白色圆角卡片,包含旋转加载圈 + 提示文字
  • 支持动态更新提示文字
  • 调用 Show() / Hide() 控制,一行代码搞定

完整代码

新建 MLoading.cs,直接复制以下代码:

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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Effects;

namespace WpfApp.Component
{
/// <summary>
/// 全局 Loading 加载遮罩组件(纯代码实现)
///
/// 使用方式:
/// MLoading.Instance.Show(this, "正在加载...");
/// // ... 异步操作 ...
/// MLoading.Instance.Hide();
///
/// // 动态更新提示文字
/// MLoading.Instance.UpdateMessage("正在处理数据...");
/// </summary>
public class MLoading
{
#region 单例

private static MLoading? _instance;
private static readonly object _lock = new();

public static MLoading Instance
{
get
{
if (_instance == null)
{
lock (_lock)
{
_instance ??= new MLoading();
}
}
return _instance;
}
}

#endregion

#region 字段

private Grid? _overlay;
private Window? _currentWindow;

#endregion

#region 显示与隐藏

/// <summary>
/// 显示 Loading 遮罩
/// </summary>
/// <param name="window">目标窗口</param>
/// <param name="message">提示消息</param>
public void Show(Window window, string message = "加载中...")
{
if (_overlay != null) { return; }

_currentWindow = window;
_overlay = CreateOverlay(message);

var rootGrid = FindRootGrid(window);
if (rootGrid != null)
{
Grid.SetRowSpan(_overlay, int.MaxValue);
Grid.SetColumnSpan(_overlay, int.MaxValue);
rootGrid.Children.Add(_overlay);
}
else
{
// 根元素不是 Grid,包装一层
var oldContent = window.Content;
var newRoot = new Grid();
window.Content = newRoot;
if (oldContent != null)
{
newRoot.Children.Add(oldContent as UIElement);
}
newRoot.Children.Add(_overlay);
}
}

/// <summary>
/// 隐藏 Loading 遮罩
/// </summary>
public void Hide()
{
if (_overlay == null || _currentWindow == null) { return; }

var rootGrid = FindRootGrid(_currentWindow);
rootGrid?.Children.Remove(_overlay);

_overlay = null;
_currentWindow = null;
}

/// <summary>
/// 更新 Loading 提示文字
/// </summary>
public void UpdateMessage(string message)
{
if (_overlay == null) { return; }

var textBlock = FindVisualChild<TextBlock>(_overlay, "LoadingMessage");
if (textBlock != null)
{
textBlock.Text = message;
}
}

#endregion

#region 创建遮罩

private static Grid CreateOverlay(string message)
{
// 旋转动画
var rotateTransform = new RotateTransform();
var animation = new DoubleAnimation
{
From = 0,
To = 360,
Duration = TimeSpan.FromMilliseconds(1000),
RepeatBehavior = RepeatBehavior.Forever
};

// 加载圈(渐变边框旋转)
var spinner = new Border
{
Width = 48,
Height = 48,
Margin = new Thickness(0, 0, 0, 16),
RenderTransform = rotateTransform,
RenderTransformOrigin = new Point(0.5, 0.5),
Background = new SolidColorBrush(Colors.Transparent),
CornerRadius = new CornerRadius(24),
BorderBrush = new LinearGradientBrush(
Color.FromRgb(33, 150, 243),
Colors.Transparent,
90),
BorderThickness = new Thickness(4)
};

// 启动旋转
rotateTransform.BeginAnimation(RotateTransform.AngleProperty, animation);

return new Grid
{
Background = new SolidColorBrush(Color.FromArgb(128, 0, 0, 0)),
VerticalAlignment = VerticalAlignment.Stretch,
HorizontalAlignment = HorizontalAlignment.Stretch,
Children =
{
new Border
{
VerticalAlignment = VerticalAlignment.Center,
HorizontalAlignment = HorizontalAlignment.Center,
Background = new SolidColorBrush(Colors.White),
CornerRadius = new CornerRadius(8),
Padding = new Thickness(32),
Effect = new DropShadowEffect
{
BlurRadius = 15,
ShadowDepth = 2,
Opacity = 0.2
},
Child = new StackPanel
{
Orientation = Orientation.Vertical,
Children =
{
spinner,
new TextBlock
{
Name = "LoadingMessage",
Text = message,
FontSize = 14,
Foreground = new SolidColorBrush(Color.FromRgb(51, 51, 51)),
HorizontalAlignment = HorizontalAlignment.Center
}
}
}
}
}
};
}

#endregion

#region 工具方法

/// <summary>
/// 查找窗口的根 Grid
/// </summary>
private static Grid? FindRootGrid(Window window)
{
return window.Content as Grid;
}

/// <summary>
/// 递归查找指定名称的子元素
/// </summary>
private static T? FindVisualChild<T>(DependencyObject parent, string name) where T : FrameworkElement
{
var count = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < count; i++)
{
var child = VisualTreeHelper.GetChild(parent, i);
if (child is T target && target.Name == name)
{
return target;
}

var result = FindVisualChild<T>(child, name);
if (result != null) { return result; }
}
return null;
}

#endregion
}
}

使用方式

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
// 基本用法
private async void Button_Click(object sender, RoutedEventArgs e)
{
MLoading.Instance.Show(this, "正在加载...");

try
{
await SomeAsyncOperation();
}
finally
{
MLoading.Instance.Hide();
}
}

// 动态更新提示文字
private async void ProcessData_Click(object sender, RoutedEventArgs e)
{
MLoading.Instance.Show(this, "正在下载...");
await DownloadAsync();

MLoading.Instance.UpdateMessage("正在解析...");
await ParseAsync();

MLoading.Instance.UpdateMessage("正在保存...");
await SaveAsync();

MLoading.Instance.Hide();
}

设计要点

1. 全屏遮罩 + 事件阻断

遮罩用半透明黑色 Grid#80000000)覆盖整个窗口,Grid 默认会捕获鼠标事件,防止用户在加载期间点击其他按钮。

2. 旋转加载圈

Border + LinearGradientBrush(蓝色 → 透明)做渐变圆环,配合 RotateTransform 每秒旋转一圈。效果类似 Material Design 的 CircularProgressIndicator。

3. 自动适配 Grid 布局

如果窗口根元素是 Grid,遮罩通过 Grid.SetRowSpan(int.MaxValue) 跨所有行;如果不是 Grid,自动包装一层。

4. 单例防重复

_overlay != null 时直接 return,防止多次调用 Show() 叠加多个遮罩。