У меня есть приложение WPF с двумя окнами xaml, одно из которых называется MainWindow.xaml
, а другое - addNewsWindow.xaml
.
В MainWindow.xaml
у меня есть DocumentViewer
и кнопка с именем Add News
, которая переводит меня в другое окно с именем AddNewsWindow.xaml
.
Это мой DocumentViewer
элемент управления в MainWindow.xaml
:
<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
у меня есть множество элементов управления для ввода данных пользователем и кнопка для просмотра и выбора файла слова, который будет отображаться в DocumentViewer
в MainWindow.xaml
:

Проблема:
При кодировании события щелчка для кнопки «Добавить» в addNewsWindow.xaml
(при нажатии которого нужно взять файл слова, преобразовать его в XPS и поместить в просмотрщик документов в MainWindow
), я не могу ссылаться на MainWindow DocumentViewer
и поместите преобразованный файл 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 не существует в текущем контексте
Я не знаю, как ссылаться на DocumentViewer
в MainWindow
из AddnewsWindow.cs