Execute code when a WPF closes - wpf

I am not familiar with using event handlers, and I was wondering if anyone had or could direct me to some code that shows how to use an event handler that will execute code on the Close/Closed event?
I know this can be done because of this answered question:
Run code on WPF form close
But I need some direction.
Thank you =)

It's just this XAML
<Window ... Closing="Window_Closing" Closed="Window_Closed">
...
</Window>
and code for both the Closing and Closed events
private void Window_Closing(object sender, CancelEventArgs e)
{
...
}
private void Window_Closed(object sender, EventArgs e)
{
....
}

If you want to do it all from code behind put this in your windows .cs file
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.Closed += new EventHandler(MainWindow_Closed);
}
void MainWindow_Closed(object sender, EventArgs e)
{
//Put your close code here
}
}
}
If you want to do part in xaml and part in code behind do this in xaml
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525" Closed="MainWindow_Closed">
<Grid>
</Grid>
</Window>
and this in .cs
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
void MainWindow_Closed(object sender, EventArgs e)
{
//Put your close code here
}
}
}
The above to examples you can apply to any form in a xaml app. You can have multiple forms. If you want to apply code for the entire application exit process modify your app.xaml.cs file to this
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
protected override void OnExit(ExitEventArgs e)
{
try
{
//Put your special code here
}
finally
{
base.OnExit(e);
}
}
}
}

You can override the OnExit function in App.Xaml.cs like this:
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
protected override void OnExit(ExitEventArgs e)
{
//do your things
base.OnExit(e);
}
}

If you are using C# on Microsoft Visual Studio, the following worked for me.
In your Window.cs file
using System;
using System.ComponentModel;
using System.Windows.Forms;
namespace Name_Space
{
public partial class Window : Form
{
public Window()
{
InitializeComponent();
//...
}
private void Window_Load(object sender, EventArgs e)
{
//...
}
private void Window_Closed(object sender, EventArgs e)
{
// Your code goes here...!
}
}
}
In your Window.Designer.cs file add this line to the following method
...
private void InitializeComponent()
{
...
//
// Window
//
...
this.Closed += new System.EventHandler(this.Window_Closed); // <-- add this line
}
...

Related

wpf component connector explicitly stated multiple time

My project contains 2 wpf apps and it seems like they are conflicting when i attempt to initialize component. The solution is called MainProject.V3
First wpf titled "Game1"
namespace MainProject.V3
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
public void MainGame(object sender, RoutedEventArgs e)
{
}
Second is called "MainMenu":
namespace MainProject.V3
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
MainWindow()
{
InitializeComponent();
}
}
}

WPF Commands. Textbox does not handle char mapped as a hotkey

I'm stuck with wpf commands and "non-trivial" hotkeys. I want to map "+" key to some command. Within i want it to keep working with any textbox. Below is the sample
Commands.cs
public static class Commands
{
private static readonly ICommand _someCommand;
static Commands()
{
_someCommand = new RoutedCommand("cmd", typeof(Commands), new InputGestureCollection { new KeyGesture(Key.OemPlus), new KeyGesture(Key.Add) });
}
public static ICommand SomeCommand
{
get { return _someCommand; }
}
}
MainWindow.xaml
<Window x:Class="WpfHotkeysTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:wpfHotkeysTest="clr-namespace:WpfHotkeysTest"
Title="MainWindow" Height="350" Width="525">
<Window.CommandBindings>
<CommandBinding Command="wpfHotkeysTest:Commands.SomeCommand" Executed="CommandBinding_OnExecuted"></CommandBinding>
</Window.CommandBindings>
<TextBox></TextBox>
</Window>
MainWindow.xaml.cs
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void CommandBinding_OnExecuted(object sender, ExecutedRoutedEventArgs e)
{
Debug.WriteLine("COMMAND! " + e.Source);
}
}
The problem is when im focused on the textbox it does not handle pressed "+" key before command is executed.
I want my key be displayed, but how do i achieve this in the best way?
UPD
I dont want to execute command if the key was handled by the text box.
I know there is property CanExecuteRoutingEventArgs.ContinueRouting. But it executes both command and textbox handling
The workaround I've found so far
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void CommandBinding_OnExecuted(object sender, ExecutedRoutedEventArgs e)
{
Debug.WriteLine("COMMAND! " + e.Source);
}
private void CommandBinding_OnCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
if (IsEditableControlSelected())
{
e.ContinueRouting = true;
return;
}
e.CanExecute = true;
}
private bool IsEditableControlSelected()
{
return Keyboard.FocusedElement is TextBox;
}
}
This brings tears to my eyes, but at least this is better than nothing. Waiting for more solutions

WPF interoperability - how can I get the including Form object from the WPF control?

I have a form of Form1 class and a WPF user control inside it (inside ElementHost). How can I get the Form1 object from this control's code-behind?
Here is the code:
/// <summary>
/// Interaction logic for UserControl1.xaml
/// </summary>
public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
}
private void Btn_Click(object sender, RoutedEventArgs e)
{
// I'd like to access the form here
}
}

DataContext in Window_Loaded

I'm very new to WPF. I'm currently doing a code to detect joints coordinate using the Kinect SDK and displaying on a simple textbox in WPF. The code to detect joints are in a private void Window_Loaded(object sender, RoutedEventArgs e) method. To display the coordinates, I used DataContext. Without further ado, let's just see the XAML code:
<Window x:Class="Prototype.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="480" Width="640">
<Grid>
<TextBox x:Name="coordinateText" Width="150" Height="20" Margin="441,409,27,12" Text="{Binding Path=xInfo}"/>
</Grid>
And this is my C# code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Research.Kinect.Nui;
using Coding4Fun.Kinect.Wpf;
namespace Prototype
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
//this.DataContext = new Coordinate { xInfo = "5" };
}
Runtime nui = new Runtime();
private void Window_Loaded(object sender, RoutedEventArgs e)
{
this.DataContext = new Coordinate { xInfo = "5" };
nui.Initialize(RuntimeOptions.UseSkeletalTracking); //code for detecting joints
//some code for detecting joints
}
public class Coordinate
{
public string xInfo { get; set; }
public string yInfo { get; set; }
public string zInfo { get; set; }
}
}
}
The thing is the information will not be loaded in the textbox if this.DataContext = new Coordinate { xInfo = "5" }; is not placed in the MainWindow. I have to put it in the Window_Loaded method. Any solutions?
As Coder323 said When window is loaded you need tell WPF TextBox that the Value of the variable xInfo is changed so you should use INotifyPropertyChanged in your Model Class
then where ever you change theValue of your Object it will pick up the changed Value... also
Just Set the DataContext=myCordinate in the Window Constructor then, make my cordinate a variable in the window class.
public class Coordinate : INotifyPropertyChanged
{
private string xInfo;
public string XInfo {
get{retun value};
set{
xInfo=Value;
FirePropertyChanged("XInfo")
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void FirePropertyChanged(string propertyName)
{
var handler = PropertyChanged;
if (handler != null)
{
handler.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
Do this for other properties and now you can set the value of myCordinate.XInfo="what ever you like" in any event it will notify to your view that the respective property has changed..
I am putting my complete solution here
My Coordinate class
public class Coordinates : INotifyPropertyChanged
{
private string xInfo;
#region Implementation of INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
public string XInfo
{
get { return xInfo; }
set
{
xInfo = value;
InvokePropertyChanged(new PropertyChangedEventArgs("XInfo"));
}
}
public void InvokePropertyChanged(PropertyChangedEventArgs e)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, e);
}
#endregion
}
My Xaml
<Window x:Class="TestApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525" Loaded="Window_Loaded">
<Grid>
<TextBox Text="{Binding Path=XInfo}" Height="30" Widht="100"></TextBox>
</Grid>
My Xaml.cs
namespace TestApp
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private Coordinates myCoordinates;
public MainWindow()
{
myCoordinates=new Coordinates();
this.DataContext = myCoordinates;
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
myCoordinates.XInfo = "Acbd";
}
}
}
And yes this test Project i made... is working
This might Help :)

Cancel a window closing in WPF

I am aware that this question is very similar to this one, but I would have thought the following code would have canceled the shutdown request, but it doesn't? Can anyone explain why?
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.Closing += new System.ComponentModel.CancelEventHandler(MainWindow_Closing);
}
private void button1_Click(object sender, RoutedEventArgs e)
{
Application.Current.Shutdown();
}
void MainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
e.Cancel = true;
}
}
}
From MSDN:
Important: When Shutdown is called,
the application will shut down
irrespective of whether the Closing
event of any open windows is canceled.

Resources