利用wpf做一个加载等待界面,当上位机发出命令后触发,接收到命令截止,写出代码
时间: 2024-03-06 22:46:11 浏览: 66
wpf加载等待动画(loading)
5星 · 资源好评率100%
以下是一个简单的加载等待界面,当上位机发出命令后触发,接收到命令截止的WPF代码:
```csharp
// XAML代码
<Window x:Class="LoadWaitWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="LoadWaitWindow" Height="150" Width="350">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<StackPanel Grid.Row="0" VerticalAlignment="Center" HorizontalAlignment="Center">
<TextBlock Text="正在加载,请稍等..." FontSize="16" FontWeight="Bold"/>
<ProgressBar Width="200" Height="20" Margin="0,20,0,0"/>
</StackPanel>
<Button Grid.Row="1" Margin="0,10,0,10" Width="100" Height="30" Content="取消" Click="CancelButton_Click"/>
</Grid>
</Window>
// C#代码
public partial class LoadWaitWindow : Window
{
private CancellationTokenSource _cancellationTokenSource;
public LoadWaitWindow()
{
InitializeComponent();
}
public async Task ShowAndWait(CancellationTokenSource cancellationTokenSource)
{
_cancellationTokenSource = cancellationTokenSource;
Show();
try
{
await Task.Delay(1000, cancellationTokenSource.Token); // 模拟加载过程
}
catch (TaskCanceledException)
{
Close();
}
}
private void CancelButton_Click(object sender, RoutedEventArgs e)
{
_cancellationTokenSource.Cancel();
}
}
```
在使用时,可以先创建一个 `CancellationTokenSource` 对象,当需要显示加载等待界面时,调用 `ShowAndWait` 方法并传入 `CancellationTokenSource` 对象,当需要结束加载等待界面时,调用 `CancellationTokenSource` 的 `Cancel` 方法即可。例如:
```csharp
private CancellationTokenSource _cancellationTokenSource;
private async Task ExecuteCommand()
{
_cancellationTokenSource = new CancellationTokenSource();
var loadWaitWindow = new LoadWaitWindow();
await loadWaitWindow.ShowAndWait(_cancellationTokenSource);
// 执行命令
// ...
loadWaitWindow.Close();
}
```
阅读全文