How to access controller from one window in another window in WPF
I have a WPF application with two xaml windows, one named MainWindow.xamland other is addNewsWindow.xaml.
In MainWindow.xaml I have a DocumentViewer and a button named Add News that takes me to the other window named AddNewsWindow.xaml.
This is my DocumentViewer control in 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">

On my addNewsWindow.xaml I have lots of controls to take user input and a button to browse and select word file, which to be displayed in the DocumentViewer in the MainWindow.xaml:

The problem:
When coding the click event for the Add button in the addNewsWindow.xaml (which when pressed should take the word file convert it to XPS and put in the Document viewer in MainWindow), I can't reference to the MainWindow DocumentViewer and put the converted XPS file into the 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();
    }
}
I get the error:
The name docViewer does not exist in the current context
I don't know how to reference the DocumentViewer in MainWindow from the AddnewsWindow.cs
c# wpf controls
add a comment |
I have a WPF application with two xaml windows, one named MainWindow.xamland other is addNewsWindow.xaml.
In MainWindow.xaml I have a DocumentViewer and a button named Add News that takes me to the other window named AddNewsWindow.xaml.
This is my DocumentViewer control in 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">

On my addNewsWindow.xaml I have lots of controls to take user input and a button to browse and select word file, which to be displayed in the DocumentViewer in the MainWindow.xaml:

The problem:
When coding the click event for the Add button in the addNewsWindow.xaml (which when pressed should take the word file convert it to XPS and put in the Document viewer in MainWindow), I can't reference to the MainWindow DocumentViewer and put the converted XPS file into the 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();
    }
}
I get the error:
The name docViewer does not exist in the current context
I don't know how to reference the DocumentViewer in MainWindow from the AddnewsWindow.cs
c# wpf controls
add a comment |
I have a WPF application with two xaml windows, one named MainWindow.xamland other is addNewsWindow.xaml.
In MainWindow.xaml I have a DocumentViewer and a button named Add News that takes me to the other window named AddNewsWindow.xaml.
This is my DocumentViewer control in 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">

On my addNewsWindow.xaml I have lots of controls to take user input and a button to browse and select word file, which to be displayed in the DocumentViewer in the MainWindow.xaml:

The problem:
When coding the click event for the Add button in the addNewsWindow.xaml (which when pressed should take the word file convert it to XPS and put in the Document viewer in MainWindow), I can't reference to the MainWindow DocumentViewer and put the converted XPS file into the 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();
    }
}
I get the error:
The name docViewer does not exist in the current context
I don't know how to reference the DocumentViewer in MainWindow from the AddnewsWindow.cs
c# wpf controls
I have a WPF application with two xaml windows, one named MainWindow.xamland other is addNewsWindow.xaml.
In MainWindow.xaml I have a DocumentViewer and a button named Add News that takes me to the other window named AddNewsWindow.xaml.
This is my DocumentViewer control in 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">

On my addNewsWindow.xaml I have lots of controls to take user input and a button to browse and select word file, which to be displayed in the DocumentViewer in the MainWindow.xaml:

The problem:
When coding the click event for the Add button in the addNewsWindow.xaml (which when pressed should take the word file convert it to XPS and put in the Document viewer in MainWindow), I can't reference to the MainWindow DocumentViewer and put the converted XPS file into the 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();
    }
}
I get the error:
The name docViewer does not exist in the current context
I don't know how to reference the DocumentViewer in MainWindow from the AddnewsWindow.cs
c# wpf controls
c# wpf controls
edited Jan 19 at 21:32
marc_s
576k12811111258
576k12811111258
asked Jan 19 at 20:33


Veliko KosevVeliko Kosev
571110
571110
add a comment |
add a comment |
                                1 Answer
                            1
                        
active
oldest
votes
It's not clear how you're creating and showing the AddNewsWindow. It may be possible for you to pass the MainWindow to the AddNewsWindow (via this):
var addNewsWindow = new AddNewsWindow(this);
The MainWindow could define a method to update the document:
public void SetDocument(XpsDocument xpsDocument)
{
    docViewer.Document = xpsDocument.GetFixedDocumentSequence();
}
Then, from AddNewsWindow, you can call:
mainWindow.SetDocument(xpsDocument);
Alternatively, instead of passing the MainWindow to the AddNewsWindow, you may be able to obtain the MainWindow directly:
var mainWindow = (MainWindow)Application.Current.MainWindow;
The reason you need to cast it is that Application.Current.MainWindow returns an instance of Window, not your MainWindow. You'll need MainWindow in order to call its SetDocument method.
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54271135%2fhow-to-access-controller-from-one-window-in-another-window-in-wpf%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
                                1 Answer
                            1
                        
active
oldest
votes
                                1 Answer
                            1
                        
active
oldest
votes
active
oldest
votes
active
oldest
votes
It's not clear how you're creating and showing the AddNewsWindow. It may be possible for you to pass the MainWindow to the AddNewsWindow (via this):
var addNewsWindow = new AddNewsWindow(this);
The MainWindow could define a method to update the document:
public void SetDocument(XpsDocument xpsDocument)
{
    docViewer.Document = xpsDocument.GetFixedDocumentSequence();
}
Then, from AddNewsWindow, you can call:
mainWindow.SetDocument(xpsDocument);
Alternatively, instead of passing the MainWindow to the AddNewsWindow, you may be able to obtain the MainWindow directly:
var mainWindow = (MainWindow)Application.Current.MainWindow;
The reason you need to cast it is that Application.Current.MainWindow returns an instance of Window, not your MainWindow. You'll need MainWindow in order to call its SetDocument method.
add a comment |
It's not clear how you're creating and showing the AddNewsWindow. It may be possible for you to pass the MainWindow to the AddNewsWindow (via this):
var addNewsWindow = new AddNewsWindow(this);
The MainWindow could define a method to update the document:
public void SetDocument(XpsDocument xpsDocument)
{
    docViewer.Document = xpsDocument.GetFixedDocumentSequence();
}
Then, from AddNewsWindow, you can call:
mainWindow.SetDocument(xpsDocument);
Alternatively, instead of passing the MainWindow to the AddNewsWindow, you may be able to obtain the MainWindow directly:
var mainWindow = (MainWindow)Application.Current.MainWindow;
The reason you need to cast it is that Application.Current.MainWindow returns an instance of Window, not your MainWindow. You'll need MainWindow in order to call its SetDocument method.
add a comment |
It's not clear how you're creating and showing the AddNewsWindow. It may be possible for you to pass the MainWindow to the AddNewsWindow (via this):
var addNewsWindow = new AddNewsWindow(this);
The MainWindow could define a method to update the document:
public void SetDocument(XpsDocument xpsDocument)
{
    docViewer.Document = xpsDocument.GetFixedDocumentSequence();
}
Then, from AddNewsWindow, you can call:
mainWindow.SetDocument(xpsDocument);
Alternatively, instead of passing the MainWindow to the AddNewsWindow, you may be able to obtain the MainWindow directly:
var mainWindow = (MainWindow)Application.Current.MainWindow;
The reason you need to cast it is that Application.Current.MainWindow returns an instance of Window, not your MainWindow. You'll need MainWindow in order to call its SetDocument method.
It's not clear how you're creating and showing the AddNewsWindow. It may be possible for you to pass the MainWindow to the AddNewsWindow (via this):
var addNewsWindow = new AddNewsWindow(this);
The MainWindow could define a method to update the document:
public void SetDocument(XpsDocument xpsDocument)
{
    docViewer.Document = xpsDocument.GetFixedDocumentSequence();
}
Then, from AddNewsWindow, you can call:
mainWindow.SetDocument(xpsDocument);
Alternatively, instead of passing the MainWindow to the AddNewsWindow, you may be able to obtain the MainWindow directly:
var mainWindow = (MainWindow)Application.Current.MainWindow;
The reason you need to cast it is that Application.Current.MainWindow returns an instance of Window, not your MainWindow. You'll need MainWindow in order to call its SetDocument method.
answered Jan 19 at 23:15
redcurryredcurry
1,029922
1,029922
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54271135%2fhow-to-access-controller-from-one-window-in-another-window-in-wpf%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
