Problem
I have an ExitApplication
command that I want to execute when I click the ‘x’ on the main window. There does not seem to be any way to expose the Close button without overriding the control template of the window. I did not want to write code-behind even though in this case it may be the most pragmatic approach! Nonetheless, I was determined to find an alternative.
My solution (with a suggestion from a colleague) is to create an attached property for the command, and when the set property method is called, I could bind to the Closed
event which would execute the attached command. And here is my code:
public static class WindowAttachedProperties
{
public static readonly DependencyProperty
CloseCommand =
DependencyProperty.RegisterAttached(
"CloseCommand",
typeof(ICommand),
typeof(Window));
public static ICommand GetCloseCommand(
Window windowTarget)
{
throw new NotImplementedException(
"The close command attached property "+
"was not intended to be used outsite of the "+
"closing even of a window.");
}
public static void SetCloseCommand(
Window windowTarget, ICommand value)
{
windowTarget.Closed += new EventHandler(
(sender, args) =>
{
value.Execute(null);
});
}
}
I would love to hear of a ‘better’ way of doing this!
This article was originally posted at
http://www.sunmetablog.co.uk?p=178
We cannot achieve perfection but we can strive for excellence. Excellence through creativity that pushes innovation, collaboration that facilitates productivity, knowledge that empowers people and persistence that eventually pays off !
Enjoy what you do and do what you enjoy !