Syncfusion PDF не может быть загружен правильноC#

Место общения программистов C#
Ответить
Anonymous
 Syncfusion PDF не может быть загружен правильно

Сообщение Anonymous »

Я студент и пытаюсь написать читателя WPF PDF на основе Syncfusion и Dragablz, но мой PDF не может правильно представлять в главном окне. Я проверил значение LoadedDocument, и оно ноль. Я спросил ИИ и исключил много проблем, но все еще не могу найти основную причину. Я не участвую в области компьютерных наук и ничего не знаю о вещах C# или WPF, поэтому весь проект был создан с помощью AI, поэтому мне действительно нужна помощь
Это код файла mainwindow.xaml:

Код: Выделить всё






































< /code>

Это код файла mainwindow.xaml.cs: < /p>
using Microsoft.Win32;
using Syncfusion.Licensing;
using Syncfusion.Pdf.Parsing; // 需要这个用于 PdfLoadedDocument
using Syncfusion.Windows.PdfViewer; // 需要这个用于 PdfViewerControl
using System; // For Exception
using System.IO; // For Path.GetFileName
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using Dragablz; // For TabablzControl and ItemActionCallbackArgs
using System.Collections.ObjectModel; // For ObservableCollection
using System.Linq;
using System.Net.Security;
using System.Diagnostics; // For Any() and First()

namespace SimplePdfViewer
{
public partial class MainWindow : Window
{
public InterTabController InterTabController { get; } = new InterTabController();

public ObservableCollection PdfTabs { get; } = new();

public MainWindow()
{
InitializeComponent();
this.DataContext = this;

}

private void btnOpen_Click(object sender, RoutedEventArgs e)
{
var openFileDialog = new OpenFileDialog
{
Filter = "PDF Files (*.pdf)|*.pdf|All Files (*.*)|*.*",
Title = "choose PDF file"
};
if (openFileDialog.ShowDialog() == true)
{
AddPdfTab(openFileDialog.FileName);
}
}

private void AddPdfTab(string filePath)
{
// 检查文件是否存在
if (!File.Exists(filePath))
{
MessageBox.Show("file does not exist.", "error", MessageBoxButton.OK, MessageBoxImage.Error);
return;
}

// 检查是否已经打开了该文件,避免重复打开
if (PdfTabs.Any(tab => (tab.ToolTip as string) == filePath))
{
var existingTab = PdfTabs.First(tab => (tab.ToolTip as string) == filePath);
pdfTabControl.SelectedItem = existingTab; // 切换到已打开的标签页
return;
}
var pdfViewer = new PdfViewerControl();
try
{
// 加载 PDF 文件
pdfViewer.Load(filePath);
var headerPanel = new StackPanel { Orientation = Orientation.Horizontal };
// 限制文件名长度,避免标签页过长
string fileName = Path.GetFileName(filePath);
if (fileName.Length > 25)
{
fileName = fileName.Substring(0, 22) + "...";
}
var fileNameText = new TextBlock { Text = fileName, Margin = new Thickness(0, 0, 4, 0) };

var closeBtn = new Button
{
Content = "×",
Width = 20,
Height = 20,
Padding = new Thickness(0),
Margin = new Thickness(0),
VerticalAlignment = VerticalAlignment.Center,
HorizontalAlignment = HorizontalAlignment.Center
};

var tab = new TabItem
{
Header = headerPanel,
Content = pdfViewer,
ToolTip = filePath // 使用 ToolTip 存储完整文件路径,方便查找
};

closeBtn.Click += (s, e) =>
{
// 在移除标签页之前,如果 pdfViewer 加载了文档,需要卸载它以释放资源
if (pdfViewer.LoadedDocument != null)
{
pdfViewer.Unload();
}
PdfTabs.Remove(tab);
};

headerPanel.Children.Add(fileNameText);
headerPanel.Children.Add(closeBtn);

PdfTabs.Add(tab);
pdfTabControl.SelectedItem = tab; // 选中新打开的标签页

// 移除此处对 UpdateWindowTitle() 的直接调用,因为它会在 SelectionChanged 事件中被调用
// UpdateWindowTitle();
}
catch (Exception ex)
{
MessageBox.Show($"cannot load file: {ex.Message}", "error", MessageBoxButton.OK, MessageBoxImage.Error);
}
}

private void PdfTabControl_ClosingItemCallback(ItemActionCallbackArgs args)
{
if (args.DragablzItem.Content is TabItem tab) // Use DragablzItem.Content to access the TabItem
{
// 在移除标签页之前,卸载 PDF 文档以释放资源
if (tab.Content is PdfViewerControl pdfViewer &&  pdfViewer.LoadedDocument != null)
{
pdfViewer.Unload();
}
PdfTabs.Remove(tab);
}
// 当标签页移除后,SelectionChanged 事件会再次触发,从而调用 UpdateWindowTitle
// 所以这里不需要再次手动调用 UpdateWindowTitle();
}

private void Minimize_Click(object sender, RoutedEventArgs e)
{
WindowState = WindowState.Minimized;
}

private void MaximizeRestore_Click(object sender, RoutedEventArgs e)
{
if (WindowState == WindowState.Maximized)
WindowState = WindowState.Normal;
else
WindowState = WindowState.Maximized;
}

private void Close_Click(object sender, RoutedEventArgs e)
{
// 在关闭主窗口前,确保所有 PDF 文档都被卸载,释放资源
foreach (var tab in PdfTabs)
{
if (tab.Content is PdfViewerControl pdfViewer && pdfViewer.LoadedDocument != null)
{
pdfViewer.Unload();
}
}
Close();
}

private void Window_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (e.ButtonState == MouseButtonState.Pressed)
this.DragMove();
}

// --- 辅助方法 ---
// ** 已修改为匹配 SelectionChangedEventHandler 委托签名 **
public void UpdateWindowTitle(object sender, SelectionChangedEventArgs e)
{
if (pdfTabControl.SelectedItem is TabItem selectedTab && selectedTab.ToolTip is string filePath)
{
this.Title = $"my pdf reader - {Path.GetFileName(filePath)}";
}
else
{
this.Title = "my pdf reader";
}
}
}
}
среда: win10pro, Visual Studio 2022, C#, .net9.0, syncfusion29.xx.

Подробнее здесь: https://stackoverflow.com/questions/796 ... -correctly
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C#»