Resolved Accessing non-static classes from different .cs files.

jacobgtd

New member
Joined
Jul 9, 2021
Messages
4
Programming Experience
Beginner
Hi everyone! I'm relatively new to all of this, but just got super lost trying to do this one thing, so hopefully someone will be able to tell what I'm doing wrong.
Basically for the setup of my project, I have 2 page files in a WPF project. The "main" project has a frame in it that calls the second page by
calling second page:
SecondPage secondPage = new SecondPage();
viewingFrame.Content = secondPage;
Essentially what I need to do, is be able to access non static methods I have stored in the MainWindow.xmal.cs and the SecondPage.xaml.cs, but it seems like virtually every way I try to go about it, I end up with a error "an object reference is required for the non-static field, method or property.
I've tried just creating a new instance of SecondPage before every reference, but it seems like a clunky way to do it, and also doesn't solve my problem, because in the methods I have I need to access the specific SecondPage Instance so that it changes for the viewer and I can get that instances specific values.
I apologize if this is a little confusing but thanks so much for any help!
Feel free to suggest a better way to go about this multipage thing if that would solve the problem as well.
 
After a bunch of screwing around I think I figured it out - I'll leave the thread up in case any other noobs have the same question. Basically what I did was added
below public partial class MainWindow : Window:
public SecondPage secondPage = new SecondPage();
at the top of my main window file. From there I just did all the coding in the main window cs file and accessed anything in secondPage with secondPage.OBJECT

To put it in the viewing frame, now I just accessed it with
C#:
viewingFrame.Content = secondPage;

I added event handlers to objects in the secondPage by just doing:
C#:
secondPage.object.Click += example_Click;

example_click(object sender, RoutedEventArgs e)
{
    //CODE
}

Sorry, not sure if this was obvious to some people but I was so lost so here is me responding to myself :)
 
It's functional, but the not the correct way to do things.

In the WPF, the correct thing to do is for only the model at best, or the view model is shared between two views. You then get information in and out of the model or view model.

In neither WinForms nor WPF is it correct for one window or form to be hooked into the events of of controls that live in another window or form. Although you could technically do it, this breaks the object oriented programming principle of encapsulation. The correct thing to do in WPF is for the model or view model to be shared between the windows. The correct thing to do in WinForms is for data to be shared between the forms.
 
Back
Top Bottom