【发布时间】:2019-06-13 17:33:16
【问题描述】:
我有一个带有两个 xaml 窗口的 WPF 应用程序,一个名为 MainWindow.xaml,另一个是 addNewsWindow.xaml。
在MainWindow.xaml 中,我有一个DocumentViewer 和一个名为Add News 的按钮,可将我带到另一个名为AddNewsWindow.xaml 的窗口。
这是我在MainWindow.xaml 中的DocumentViewer 控件:
<DocumentViewer x:FieldModifier="public" x:Name="docViwer"
Grid.Row="2" Grid.RowSpan="4" Grid.ColumnSpan="4"
BorderBrush="Black" BorderThickness="1"
Margin="1,2,40,1">
在我的addNewsWindow.xaml 上,我有很多控件来接受用户输入,还有一个按钮来浏览和选择 word 文件,这些文件将显示在 MainWindow.xaml 中的 DocumentViewer 中:
问题:
在为addNewsWindow.xaml 中的“添加”按钮编写单击事件时(按下该按钮时应将 word 文件转换为 XPS 并放入 MainWindow 的文档查看器中),我无法引用 @ 987654339@,并将转换后的XPS文件放入DocumentViewer。
AddNewsWindow.cs
private void FilePathBtn_Click(object sender, RoutedEventArgs e)
{
// Create OpenFileDialog
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
// Set filter for file extension and default file extension
dlg.DefaultExt = ".doc";
dlg.Filter = "Word documents|*.doc;*.docx";
// Display OpenFileDialog by calling ShowDialog method
Nullable<bool> result = dlg.ShowDialog();
// Get the selected file name and display in a TextBox
if (result == true)
{
// Open document
string filename = dlg.FileName;
filePathTBox.Text = filename;
}
}
private XpsDocument ConvertWordToXps(string wordFilename, string xpsFilename)
{
// Create a WordApplication and host word document
Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();
try
{
wordApp.Documents.Open(wordFilename);
// To Invisible the word document
wordApp.Application.Visible = false;
// Minimize the opened word document
wordApp.WindowState = WdWindowState.wdWindowStateMinimize;
Document doc = wordApp.ActiveDocument;
doc.SaveAs(xpsFilename, WdSaveFormat.wdFormatXPS);
XpsDocument xpsDocument = new XpsDocument(xpsFilename, FileAccess.Read);
return xpsDocument;
}
catch (Exception ex)
{
MessageBox.Show("Error occurs, The error message is " + ex.ToString());
return null;
}
finally
{
wordApp.Documents.Close();
((_Application)wordApp).Quit(WdSaveOptions.wdDoNotSaveChanges);
}
}
private void AddNewsBtn_Click(object sender, RoutedEventArgs e)
{
string wordDocument = filePathTBox.Text;
if (string.IsNullOrEmpty(wordDocument) || !File.Exists(wordDocument))
{
MessageBox.Show("The file is invalid. Please select an existing file again.");
}
else
{
string convertedXpsDoc = string.Concat(System.IO.Path.GetTempPath(), "\\", Guid.NewGuid().ToString(), ".xps");
XpsDocument xpsDocument = ConvertWordToXps(wordDocument, convertedXpsDoc);
if (xpsDocument == null)
{
return;
}
// MainWindow.docViewer = xpsDocument.GetFixedDocumentSequence();
docViewer.Document = xpsDocument.GetFixedDocumentSequence();
}
}
我得到错误:
名称docViewer在当前上下文中不存在
我不知道如何从AddnewsWindow.cs 引用MainWindow 中的DocumentViewer
【问题讨论】: