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
public static ICommand GetCloseCommand(
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) =>
I would love to hear of a ‘better’ way of doing this!
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 !