2

I'm developing a WPF and C# application and i have problems to pass data between a page and a window.

How is the best way to do it?

Thanks!

Rodrigo Guedes
  • 1,169
  • 2
  • 13
  • 27
Rubén
  • 31
  • 1
  • 5
  • Check this out: [http://stackoverflow.com/questions/4517214/windows-messaging-trapping-calls-originating-from-another-api][1] [1]: http://stackoverflow.com/questions/4517214/windows-messaging-trapping-calls-originating-from-another-api – Steve Sep 18 '13 at 17:06

2 Answers2

2

You can use a delegateevent to do this. For example in your MainWindow :

namespace WpfApplication1
{
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        Page1.onNameSend += Page1_onNameSend;
    }

    void Page1_onNameSend(string Name)
    {
        Console.WriteLine(Name);
    }
}
}

And then in your Page1:

namespace WpfApplication1
{
public partial class Page1 : Page
{
    public delegate void SendName(string Name);

    public static event SendName onNameSend;

    public Page1()
    {
        InitializeComponent();
    }

    private void SendButton(object sender, RoutedEventArgs e)
    {
        onNameSend("Name to Send");
    }
}
}

Hope that helps.

oimitro
  • 1,466
  • 4
  • 14
  • 22
  • 1
    Such an event likely shouldn't be static; it should be an instance event. There's also no real need to define a new delegate, just use `Action` here. You also should null check the event, so it doesn't throw a NRE if there are no handlers. It's also odd to call it a "delegate event". It's just an event. – Servy Sep 18 '13 at 17:32
  • You are absolutely right. But i just wanted to give him an idea or a starting point, so he can work with it.But every comment is welcome. – oimitro Sep 18 '13 at 17:37
  • And all of the things that I mentioned would be easy enough to change for an intermediate or experienced developer, but not for a new developer. As such (mostly the first and third points, the second isn't a "problem" so much as a stylistic change) not addressing these issues could result in serious problems down the road that readers may have a very tough time tracking down and fixing. Leaving those issues there is highly irresponsible. – Servy Sep 18 '13 at 17:40
  • Couldnt agree more with you. – oimitro Sep 18 '13 at 17:45
  • worked for me! I would like to see those changes @Servy – wdlax11 Jul 24 '18 at 15:25
-2

I recently had this issue and was able to solve with public application properties. i do not know if this is the "best practice" in fact I doubt it but it can solve the issue.

//creating a new property
Application.Current.Properties["accessName"] = newPropertyValue;

//retrieving

RecievingWindowVariable = (castDataType)Application.Current.Properties["accessName"];
asuppa
  • 571
  • 1
  • 11
  • 27