(WPF) Does .Close() method releases the window instance? - wpf

I'm creating a new window in On_Click method. First I tried this;
public partial class MainWindow : Window
{
CustomerOperations customerOperationsWindow;
public MainWindow()
{
customerOperationsWindow = new CustomerOperations();
InitializeComponent();
}
private void btnCustomer_Click(object sender, RoutedEventArgs e)
{
customerOperationsWindow.Owner = this;
customerOperationsWindow.Show();
}
}
It's not working so I started creating the window instance every time the user clicks on the Customers button. And I used the following codes.
private void btnCustomer_Click(object sender, RoutedEventArgs e)
{
CustomerOperations customerOperationsWindow = new CustomerOperations();
customerOperationsWindow.Owner = this;
customerOperationsWindow.Show();
}
In the new window, If user clicks to Main button, I want to navigate to main window.
private void btnMain_Click(object sender, RoutedEventArgs e)
{
this.Close();
this.Owner.Show();
}
First question: Does this.Close() releases the window instance?
Second question: Is this usage correct?
What do you think is the best practice?
Thank you all.

Window.Close() will dispose all resources allocated by the instance. That's why you cannot show it again once it was closed.
If you want to reuse the same Window instance, you should cancel the closing procedure to prevent disposal of internal resources and collapse the Window instead (by setting Window.Visibility to Visibility.Collapsed - Visibility.Collapsed is also the default value of an instantiated Window before Window.Show() is called).
Alternatively hide the Window by calling Window.Hide() (which will set the Visibility to Visibility.Hidden) instead of Window.Close().
Calling Window.Show will also set the window's visibility to Visibility.Visible.
As a matter of fact, showing a Window by setting Window.Visibility is the asynchronous version of Window.Show().
Generally, you switch between Window instances by using the Window.Activate method. Calling Window.Show on a Window that is currently showing/visible, does nothing.
public partial class MainWindow : Window
{
CustomerOperations CustomerOperationsWindow { get; }
public MainWindow()
{
InitializeComponent();
this.CustomerOperationsWindow = new CustomerOperations();
// Consider to move this logic to CustomerOperations class,
// where you can override the OnClosing method instead of subscribing to the event
this.CustomerOperationsWindow.Closing += CollapseWindow_OnClosing;
}
// Cancel close to prevent disposal and collapse Window instead
private void CollapseWindow_OnClosing(object sender, CancelEventArgs e)
{
e.Cancel = true;
this.CustomerOperationsWindow.Visibility = Visibility.Collapsed;
this.CustomerOperationsWindow.Owner.Activate();
}
private void btnCustomer_Click(object sender, RoutedEventArgs e)
{
this.CustomerOperationsWindow.Owner = this;
// Calling Show will set the Visibility to Visibility.Visible
this.CustomerOperationsWindow.Show();
}
}
Creating a Window instance allocates unmanaged resources. If this happens very frequently, you will keep the garbage collector busy. From a performance point of view you may want to avoid it and prefer to reuse the same instance.
In a common scenario this is not necessary. But since Window exposes a Hide() method, you may consider to use it instead of Close().

If you want to switch to the parent window, you can use the code this.Owner.Activate(); and if you want to close the current window, first this.Owner.Activate(); and then this.Close();.
When you enter this.Close(), the compiler does not execute the following lines after reaching it. And when a sample window still exists there is no need to recreate it
private void btnMain_Click(object sender, RoutedEventArgs e)
{
this.Owner.Activate();
this.Close();
}

Related

Show() window wait for a button to be pressed and mainWindow active (WPF)

InteractiveWindow contain YES and NO button. The current solution is displaying the InteractiveWindow on MainWIndow without having access to MainWindow. InteractiveWindow is also a Window (not a UserControl). How is possible to transform my dialog window in order to have my InteractiveWindow on top of my MainWindow and be able to access MainWindow until one of the two buttons are pressed?
internal async Task<bool> Test()
{
// some code
var test= new InteractiveWindow();
test.Owner = this;
test.ShowDialog();
// some other code
return true;
}
Old code for one of the button:
private void YES_Click(object sender, RoutedEventArgs e)
{
GetWindow(this).DialogResult = true;
this.Close();
}
You should use
test.Show()
instead of test.ShowDialog(), because ShowDialog() is blocking. Even though your method is async, it executes synchronously until it needs to await an incomplete Task, so your Test method is blocking because there is no such await statement. I suggest you remove this async modifier if you don't use it.

How do I show windows sequentially in WPF?

I have the following code in App.xaml.cs:
protected override void OnStartup(StartupEventArgs e)
{
var window = new WelcomeWindow();
if (window.ShowDialog() == true)
{
var mainWindow = new MainWindow();
mainWindow.ShowDialog();
}
}
The second window never shows. Instead, the application simply closes when the Welcome window is closed. How do I ensure a second window can be shown after a first one is closed?
This is because default value of Application.ShutdownMode is OnLastWindowClose. This means when your WelcomeWindow is closed the application shuts down and you see nothing more.
To solve this set ShutdownMode to OnExplicitShutdown and call Shutdown explicitly if you want to exit your app.
public App()
{
this.ShutdownMode = ShutdownMode.OnExplicitShutdown;
}
What about to show WelcomeWindow on Initialized event of MainWindow and close last if Dialog is not true. This was you let MainWindow to stay the MainWindow of Application.
private void Window_Initialized(object sender, EventArgs e)
{
// at this moment MainWindow is Initialized but still nonvisible
if ((new WelcomeWindow()).ShowDialog()!=true)
{
this.Close();
}
}
When you load any window Application_Startup it become The MainWindow of application. And it will closed on this window closing.
I've checked that even if you have StartupUri="MainWindow.xaml" in you app.xaml it have no effect if some else window have been shown on Application StartUp event.
You may do it yourself. Just make breakpoint on your firstloaded window Loaded event handler and look in debuger on "Aplication.Current.MainWindow == this" expression result. It will be true.

WPF - Toggle Visibility of multiple windows

i will first explain the UI of my WPF App.
I have created a window which contains many buttons which is always visible to the user(lets call it main window), each button will open a new window relevant to the task. what i want done is that whenever a button is clicked, the main window should be hidden(visibility : collapsed) and the new window should be shown. This second window will also contain a button which will hide the second window and show back the main window.
also the second window which will be opening will have different dimensions as per the command associated with it so i will be having different windows for eaach
TLDR i want to be able to switch between multiple windows such that only one window is visible at one time, how do i manage the switching between multiple windows ??
Note : I can show the second window from main window but what about showing main from the second window....can't get it....or if anyone can show me a different approach to implement this : other than multiple windows
Also, this is an extension to the UI, i want to show the buttons in this crystalised sort of look like on this page : http://postimage.org/image/4yibiulsh/
can anyone direct me to a proper implementation, i have been through many sites and also tried to create these through blend but i just am not a UI Person....pls need help on this
Thanks in advance.
I would create a "Window manager" which will subscribe to the changes of opening/closing.
In this case you don't have to overload Window classes.
Example (worked for me).
public class WindowsManager
{
static readonly List<Window> Windows=new List<Window>();
public static T CreateWindow<T>(T window) where T:Window
{
Windows.Add(window);
window.Closed += WindowClosed;
window.IsVisibleChanged += WindowIsVisibleChanged;
return window;
}
static void WindowIsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
{
var mainWindow = Application.Current.Windows.OfType<MainWindow>().Single();
mainWindow.Visibility = Equals(e.NewValue, true) ? Visibility.Hidden : Visibility.Visible;
}
static void WindowClosed(object sender, System.EventArgs e)
{
var window = (Window) sender;
window.Closed -= WindowClosed;
window.IsVisibleChanged -= WindowIsVisibleChanged;
Windows.Remove(window);
}
}
How to use:
private void button1_Click(object sender, RoutedEventArgs e)
{
WindowsManager.CreateWindow(new Child1()).Show();
}
private void button2_Click(object sender, RoutedEventArgs e)
{
WindowsManager.CreateWindow(new Child2()).Show();
}
So, when the child window will close, WindowsManager will be notified about this and will update visibility for the main window
UPD1.
added line to unscubscribe from VisibleChanged
You can use several approaches for that.
To easy switch back to main Window: inject a reference of your MainWindow to your SecondWindow (or any other Window you want to display) and in the Closing Event of that Window you set the Visibility of the MainWindow back to Visible.
Have you also considered keeping everything in the same Window but having different Panels that you set Visible and Invisible? That could have the same effect but it's less complicated...
Hope that helps...

WPF - removing a control that has a DispatcherTimer doesn't seem to go away

I've seen the question asked on StackOverflow on how to properly remove controls in WPF. Generally there is some comment how you don't dispose them manually(or can't) and as long as you are not holding a reference to them they will be cleared eventually by the GC. I noticed quite by accident that one of my controls that I thought I removed was sticking around and still doing work even though I removed it from its parent.
I've recreated the example in as few lines as possible. The control has a DispatcherTimer.
Here is the WPF code behind for the control I want to remove.
public partial class MyControl : UserControl
{
private DispatcherTimer timer;
public MyControl()
{
InitializeComponent();
timer = new DispatcherTimer();
timer.Tick += TimerOnTick;
timer.Interval = TimeSpan.FromSeconds(1);
timer.Start();
}
private void TimerOnTick(object sender, EventArgs args)
{
//this continues to get written out even after this control is removed.
System.Diagnostics.Debug.WriteLine("Tick From MyControl.");
}
}
Here is the code behind for a window that adds and removes my control.
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void AddClicked(object sender, RoutedEventArgs e)
{
anyControlHolder.Children.Add(new MyControl());
}
private void RemoveClicked(object sender, RoutedEventArgs e)
{
anyControlHolder.Children.Clear();
}
}
The problem I'm having when I run this code and then dynamically add and remove the custom usercontrol (MyControl) is that it's timer keeps ticking (in this example you can see it write out a message in the output window) and it keeps doing work in its tick event.
What pattern should I use to at least cause the timer to stop ticking when the control is removed?
You can hook into your control's Unloaded event and call timer.Stop() inside. I just tested this scenario, and the Unloaded event is raised when anyControlHolder.Children.Clear() was called, thus stopping the debug messages.
Code:
public partial class MyControl : UserControl {
private DispatcherTimer timer;
public MyControl() {
InitializeComponent();
this.Loaded += new RoutedEventHandler(MyControl_Loaded);
this.Unloaded += new RoutedEventHandler(MyControl_Unloaded);
}
void MyControl_Loaded(object sender, RoutedEventArgs e) {
timer = new DispatcherTimer();
timer.Tick += TimerOnTick;
timer.Interval = TimeSpan.FromSeconds(1);
timer.Start();
}
void MyControl_Unloaded(object sender, RoutedEventArgs e) {
timer.Stop();
}
private void TimerOnTick(object sender, EventArgs args) {
Debug.WriteLine("Tick From MyControl.");
}
}
Hope this helps!
The other thing I would would be to remove the event handler that you added for your tick event. Any thing that you manually add you should remove.
As far as implementing a WeakEventPattern you may want to look at this article

Multiple Command Binding

Is it possible to bind the multiple commands to the button.
I have a user control, which i am calling in my main application (parent application).
I want to handle a click command on both the controls (the user control as well as on the main window). However i am only able to get one.
Is there any way in which i can get this.
Any help is really appreciated.
Code Snippet:
public class MainWindowFooterCommands
{
public static readonly RoutedUICommand FooterClickLocalCommand = new RoutedUICommand("Local Button Command", "FooterClickLocalCommand", typeof(MainWindowFooterCommands));
}
private void MainWindowFooterBindCommands()
{
CommandBinding cmdBindingBXClick = new CommandBinding(MainWindowFooterCommands.FooterClickLocalCommand);
cmdBindingBXClick.Executed += ClickCommandHandler;
CommandBindings.Add(cmdBindingBXClick);
}
void ClickCommandHandler(object sender, ExecutedRoutedEventArgs e)
{
//Do Something
}
//Parent Control holding an instance of the footer control.
class MainWindow {
public MainWindow()
{
CommandBinding cmdBindingBXClick1 = new CommandBinding(MainWindowFooterCommands.BXClickMainWindowCommand);
cmdBindingBXClick1.Executed += LoadParent;
CommandBindings.Add(cmdBindingBXClick1);
}
public void LoadParent(object sender, ExecutedRoutedEventArgs e)
{
LoadParentWindow();
}
}
Regards,
Tushar
You might be trying to aggregate multiple commands, which is a natural thing to want to do.
If you are using Prism, there is a class builtin for this called the CompositeCommand (scroll down a bit): https://msdn.microsoft.com/en-us/library/ff921126.aspx
Otherwise, Josh Smith has a very good article on his implementation called a "Command Group": http://www.codeproject.com/KB/WPF/commandgroup.aspx
There are some very nice scenarios you can rollup like this (for instance, "Save All"). A good tool for your bag of tricks.
AFAIK WPF doesnt offer anything out of the box to support multiple commandbindings at various levels, but you could try the following:
void ClickCommandHandler(object sender, ExecutedRoutedEventArgs e)
{
IInputElement parent = (IInputElement) LogicalTreeHelper.GetParent((DependencyObject)sender);
MainWindowFooterCommands.BXClickMainWindowCommand.Execute(e.Parameter, parent);
}
You might have to test whether your parent really is an IInputElement, though.

Resources