简体   繁体   中英

How to pass data from child form event to parent form item?

Currently I have a main form, from which I call a popup that I've created in a seperate XAML file for my spellchecker. It's called like so:

SpellCheckerPopupControl popupControl = new SpellCheckerPopupControl();

popupControl.SpellChecklistBox.Items.Clear();

//some code to check the word and populate the child listbox with spelling suggestions

popupControl.SpellCheckerPopup.IsOpen = true;

I have an event setup in the child on SelectionChanged in the listbox for it to pass the data back to the main form, currently I just want to pass the selection back to my main form so that I can take the selected word and replace the misspelled one with it. Unfortunately, I don't seem to be able to pass data from the child form's events back to the parent.

The XAML for the SpellCheckerPopup is just a <PopUp> with a <ListBox> inside it.

Just for testing purposes, I've tried to just take the output of what happens and paste the string into the main textbox like so: MainPage.txtArticle.Text = s; , but while the MainPage bit is available, none of its elements are, and as such I cannot manipulate them from the child event.

Make a property of the window

var window = new popupControl.Open();

then on window.closed event check for Window.txtArticle .Text;

This should work. If not, then bind them to properties in the code behind.

[update]

Example:

var window = new MyTestChildWindow();
//This is just to show how to change properties in the testwindow.
window.SomeProperty = true;
window.Show();
window.Closed += (s, ea) =>
{
  if (window.DialogResult.ToBoolean())
  {
    // this is a property in the code behind.
    if (window.SelectedItem != null)
    {
      //Property = property on mainpage
      //window.SelectedItem = property in childwindow
      this.Property = window.SelectedItem;
    }
  }
};

this code goes in your main page.

hope this helps.

You could also create a property in your Program.cs file that you could pass a value to. Then you would have access to that property application wide. Just use:

Program.SomeProperty

Using variables, declared somewhere else is a recipe for problem as nothing will gurantee actuality of that 'external' data.

Provided your event is a routed one, you can always query for OriginalSource and obtain information from it. If your event is not a routed one, you can create an attached event and pass your popup a OriginalSource.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM