Communication between parent and child window in wpf - c#

I have a parent window which launches a child window, after doing some selection/operation in the child window is closed and I want to send some info back to the parent window (a custom class object), what's the best way to accomplish this in WPF using the features provided by WPF?

You have many options:
You could use a custom event in your child window that the parent window listens to
You could define a delegate in the child window that references a method in the parent window
You could change the constructor for the child window to take a reference to the parent window and call a method on the parent window using that reference
You could possibly use the VisualTreeHelper class to get the parent window and call a method on that reference

Extracted from this link:
The easiest way I have found to pass data from a child window to a
parent window is to use an application wide property. This property is
an object, and is not the most elegant form to pass data from a child
window to a parent, but it's the least amount of programming. The best
way to do this is using get and set accessor properties.
Create a main window (mainWindow) Create a child window (in this case,
Password)
In the main window, the child window must be shown, say, within a
button click. This window would have a button to do something, in this
case, it's to delete a record from the database.
private void btnDelete_Click(object sender, RoutedEventArgs e)
{
Password passwordentry = new Password();
passwordentry.ShowDialog();
if (Application.Current.Properties["PassGate"].ToString() == "mypassword")
{
Code, or call to delete the record;
}
Application.Current.Properties["PassGate"] = "";
}
In the child window (Password), the property for the application is
set using a textbox. This is a simple window that has a textbox called
PasswordTextBox and a couple of buttons, like Accept and Cancel.
private void AcceptButton_Click(object sender, RoutedEventArgs e)
{
Application.Current.Properties["PassGate"] = PasswordTextBox.Text;
this.Close();
}

Related

C# wpf multiple windows on task bar

I created a C# project which have multiple windows. When I do some other stuff, some of the windows are lost focus. Then I have to bring them to front by clicking the task bar one by one.
I am wondering is there are OnTaskBarClick Event on C# wpf window?
Then What I need to do is to set all sub windows with "ShowInTaskbar="False"". Then when ever my mainwindow is clicked on the task bar, I bring all the windows to the front.
You'll want to use the Window.Activated event to detect when your application's window is brought into focus:
From the documentation:
A window is activated (becomes the foreground window) when:
The window is first opened.
A user switches to a window by selecting it with the mouse, pressing ALT+TAB, or from Task Manager.
A user clicks the window's taskbar button.
Or you could use the Application.Activated event.
Clicking on a control of an already active window can also cause the Window.Activated event to fire, so if the issue is that it's firing too often, you'll probably want to watch for when the application toggles between being active and deactive.
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Application.Current.Activated += CurrentOnActivated;
Application.Current.Deactivated += CurrentOnDeactivated;
}
private bool isDeactivated = true;
private void CurrentOnDeactivated(object sender, EventArgs eventArgs)
{
isDeactivated = true;
//handle case where another app gets focus
}
private void CurrentOnActivated(object sender, EventArgs eventArgs)
{
if (isDeactivated)
{
//Ok, this app was in the background but now is in the foreground,
isDeactivated = false;
//TODO: bring windows to forefont
MessageBox.Show("activated");
}
}
}
I think what you are experiencing is the window Owner not being set on your child window.
Please refer to Window.Owner Property
When a child window is opened by a parent window by calling
ShowDialog, an implicit relationship is established between both
parent and child window. This relationship enforces certain behaviors,
including with respect to minimizing, maximizing, and restoring.
-
When a child window is created by a parent window by calling Show,
however, the child window does not have a relationship with the parent
window. This means that:
The child window does not have a reference to the parent window.
The behavior of the child window is not dependent on the behavior of the parent window; either window can cover the other, or be
minimized, maximized, and restored independently of the other.
You can easily fix this by setting the Owner property in the child window when before calling Show() or ShowDialog()
Window ownedWindow = new Window();
ownedWindow.Owner = this; // this being the main or parent window
ownedWindow.Show();
Note : if conforming to an MVVM pattern, this can become a little
more cumbersome, however there is plenty of resources on how to link owner and parent windows.

WPF Create sibling window and close current one

What I need is such an event handler in my window class.
void someEventHandler(object sender, RoutedEventArgs e)
{
MyNewWindow mnw = new MyNewWindow();
mnw.Owner = Window.GetWindow(this);
mnw.ShowDialog();
this.Close();
}
Window.GetWindow(this) returns the parent window of the current window.
I had thought when the owner of the new window is the parent window of the current one, it would wait for the parent; and not the current one. But it did not work that way. Current window waits for the execution of the new and closes only after.
If I use Show() instead of ShowDialog() for some reason the window is not shown at all.
Probably I need some delegate methods but I am not sure where to start.
Edit: I guess I need to improve the question for future references:
The new window should be a dialog to the parent window. If I use Show() the parent window becomes accesible and I dont want that. If I use ShowDialog() it becomes a dialog to the current window, meaning that the current window does not close until the new window is closed, and I dont want that either.
Closing a window causes any windows that it owns to be closed.
If you just want the owner window to not be visible, try this;
void someEventHandler(object sender, RoutedEventArgs e)
{
MyNewWindow mnw = new MyNewWindow();
mnw.Owner = this;
this.Hide(); // not required if using the child events below
mnw.ShowDialog();
}
You'll likely want to hook up some event in the parent window that acts accordingly when you close the child window depending on your requirements.
EDIT
You could perhaps control the hiding of the (multiple parents) from the child;
void OnLoad(object sender, RoutedEventArgs e)
{
this.Owner.Hide();
}
void Closed(object sender, RoutedEventArgs e)
{
this.Owner.Show();
}
If I understand what you're trying to do you want to close the current window and replace it with a MyNewWindow that is a child of the window that was the original window's parent (probably the app's main window).
To do that you should be using:
mnw.Owner = this.Owner;
instead of calling GetWindow, which gives you back the current Window instance. The purpose of GetWindow is to obtain the Window which contains some other UIElement, like a Button farther down the tree. When passing in a Window instance, you just get back what you passed in.
Calling ShowDialog() blocks. That means, the method returns only when mnw is closed and only then is the original window closed.
If you change that to Show(), mnw is closed as soon as you call Close() on the original window. because Window.GetWindow(this) returns this. Thus, you set the owner to this and when you close this, mnw gets closed too. That leaves us with:
MyNewWindow mnw = new MyNewWindow();
mnw.Owner = this.Owner; // may not be necessary
mnw.Show();
this.Close();
This code seems to work for me.

Updating textbox on mainform with a variable on a child form that is launched from main form

I have a windows form app. The main form has a textbox, and a button to launch another form. When the other form is launched, both forms are on screen (but the launched form is modal). The child form has a textbox and button, and when the button is pressed, I want the textbox on the main form (the parent) to be updated with the value in the textbox on the child form.
How is this functionality achieved?
Ideally you want to keep both forms from being dependent on each other, this could be achieved with interfaces:
public interface IMainView
{
public void UpdateValue(string val);
}
public interface IChildView
{
public void Show(IMainView parent);
}
have your main form implement IMainView and the child implement IChildView, the parent calls child.show(this) and the child calls parent.UpdateValue(blah);
Hope this helps.
If the child form is closed when the button is clicked, you could put a public property which wraps the value of the textbox on the child form. Then the main form can read this property after calling ShowDialog.
If you want this to happen without closing the child form, you can create a function on the main form to change the textbox. Then the child form would call that function.
The best ways to achive this situation are clockWize's and Hans Passants's advices.
But what about that?
Write a property for your textbox at parent form, like this.
public string TextBoxText
{
get { return txtTextBox.Text;}
set { txtTextBox.Text = value;}
}
When you are opening the child form set the owner.
ChildForm f = new ChildForm();
f.Owner = this;
f.Show();
Create an event handler to child forms button click event.
public Button1_Click(object sender; EventArgs e)
{
ParentForm f = (ParentForm)this.Owner;
f.TextBoxText = txtChildTextBox.Text;
}
i didn't compile code; so may have errors :)
}
When a button is pressed to close the launched form, returning you to the main form- the launched form's text box is still in scope.
Closing a form is merely changing the object's state, not disposing of it. So in the button eventhandler that launches the form from the main form, the next line after launching your modal window, it can access the text from the object it launched as the textbox is a child of that form's object. Unless you're launching your modal window in another thread, which I wouldn't figure you are since it's modal, when it is closed, it should go to the next line in the buttons eventhandler that launched it.
your main form may have code something like this right now (haven't done winforms in a while so bear with me if I miss something):
public void Button1_Click(object sender, ClickEventArgs e)
{
SomeFormIWantToLaunch launchForm = new SomeFormIWantToLaunch();
launchForm.ShowDialog(this);
}
You need to just add after launchForm.ShowDialog(this); something like:
this.SomeTextBox.Text = launchForm.ATextBox.Text;

c# winforms Child form load problem

I have a dialog-based application.
I need to show a child window like this:
(1) First, the application's main dialog window will show up,
(2) then, a child dialog window will show up automatically on top of that.
You know, it is not enough to call the child window's ShowDialog() in the parent window's constructor or load event. Coz in those cases, the child window will appear first.
What should I do to achieve that?
Use can use the event Shown of your main dialog, to show the child in front of you main dialog. This event is only raised once, when the main dialog is shown the first time. Also you should use the Show() (not ShowDialog) method and then call BringToFront() of your child dialog.
private void OnShown(EventArgs e) {
ChildDialog child = new ChildDialog();
child.Show(this);
child.BringToFront();
}

MDI window list not updating child title bar texts

I have a MDI container form, and some child forms that update their title bar texts themselves, independently. After the Text property is changed on the child form, the new title bar text from the child is not updated in the window list menu when the menu is opened. This is the auto-generated window list provided by .NET via the MdiWindowListItem property.
The change only propagates when another event changes the window list physically (opening a new child, closing a child, switching to another child).
Is there a way to force an update of the window list programmatically? I already have some code in place to do menu enabling/disabling at the same time the child's title bar text is changed.
I tried the following with no success:
Update() on the main MenuStrip
Refresh() on the main MenuStrip
Invalidate() on the window MenuStrip
Invalidate() on one of the window list items at runtime
Toggling the Checked state twice on one of the window list items at runtime
There don't seem to be any other remotely viable functions to call on the menu item, its parent ToolStrip, or the parent form that contains the menu system.
The above solution did not work for me. But I followed the link, and found this, which works perfectly:
private void windowMenu_DropDownOpening(object sender, EventArgs e)
{
if (this.ActiveMdiChild != null)
{
Form activeChild = this.ActiveMdiChild;
ActivateMdiChild(null);
ActivateMdiChild(activeChild);
}
}
Thank you!
You need to add a TextChanged event to the child form, with this handler:
private void childForm_TextChanged(object sender, EventArgs e) {
this.ActivateMdiChild( null );
this.ActivateMdiChild( sender as Form );
}
http://social.msdn.microsoft.com/forums/en-US/winforms/thread/a36b89aa-57aa-48b5-87a6-49fbddc9c92d
Instead of activate/deactivate, you can send WM_MDIREFRESHMENU message to the MDI client (not frame) window whenever a window title changed.
http://msdn.microsoft.com/en-us/library/windows/desktop/ms644919%28v=VS.85%29.aspx

Categories

Resources