SSPC-Tester/SSPCTester.UI/Views/ReportView.xaml.cs
2026-06-30 12:10:29 +08:00

87 lines
2.3 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System.ComponentModel;
using System.Windows.Controls;
using Microsoft.Web.WebView2.Core;
using SSPCTester.UI.ViewModels;
namespace SSPCTester.UI.Views;
public partial class ReportView : UserControl
{
private ReportViewModel? _viewModel;
public ReportView()
{
InitializeComponent();
DataContextChanged += (_, e) =>
{
if (_viewModel != null)
_viewModel.PropertyChanged -= ViewModel_PropertyChanged;
_viewModel = e.NewValue as ReportViewModel;
if (_viewModel != null)
{
_viewModel.PropertyChanged += ViewModel_PropertyChanged;
NavigatePreview(_viewModel.PreviewSource);
}
else
{
NavigateBlank();
}
};
Unloaded += (_, _) =>
{
if (_viewModel != null)
_viewModel.PropertyChanged -= ViewModel_PropertyChanged;
_viewModel = null;
NavigateBlank();
};
}
private void ViewModel_PropertyChanged(object? sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == nameof(ReportViewModel.PreviewSource) && sender is ReportViewModel vm)
NavigatePreview(vm.PreviewSource);
}
private void PdfPreview_CoreWebView2InitializationCompleted(
object? sender,
CoreWebView2InitializationCompletedEventArgs e)
{
if (e.IsSuccess) return;
if (DataContext is ReportViewModel vm)
vm.PreviewUnavailable("PDF 预览初始化失败。请确认已安装 Microsoft Edge WebView2 Runtime或使用“打开文件夹”查看报告。");
}
private void NavigatePreview(Uri? source)
{
if (source == null)
{
NavigateBlank();
return;
}
try
{
PdfPreview.Source = source;
}
catch
{
NavigateBlank();
_viewModel?.PreviewUnavailable("PDF 预览加载失败。请使用“打开文件夹”查看报告。");
}
}
private void NavigateBlank()
{
try
{
PdfPreview.Source = new Uri("about:blank");
}
catch
{
// WebView2 may not be initialized yet; leave it untouched.
}
}
}