Window.Close() from XAML

July 1, 2009

It’s been a long time since I last posted. Since then I have been working on my first WPF contract. I have definately drank the cool aid, I love WPF (when MVVM is being used anyway).

One thing I haven’t been able to find any info on is how to close a window from XAML. I tried and tried and then gave up. Until now!

Having discovered the power of Attached Behaviours, I decided to write one that would close a window. All you need do then is create a data trigger that watches a CloseSignal on the ViewModel and sets the Close property to true.

public static class WindowCloseBehaviour
    {
        public static void SetClose(DependencyObject target, bool value)
        {
            target.SetValue(CloseProperty, value);
        }

 

public static void GetClose(DependencyObject target)
        {
            return target.GetValue(CloseProperty);
        }

        public static readonly DependencyProperty CloseProperty =
            DependencyProperty.RegisterAttached(
            “Close”,
            typeof(bool),
            typeof(WindowCloseBehaviour),
            new UIPropertyMetadata(false, OnClose));

        private static void OnClose(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            if (e.NewValue is bool && ((bool)e.NewValue))
            {
                Window window = GetWindow(sender);
                if (window != null)
                    window.Close();
            }
        }

        private static Window GetWindow(DependencyObject sender)
        {
            Window window = null;

            if (sender is Window)
                window = (Window)sender;

            if (window == null)
                window = Window.GetWindow(sender);

            return window;
        }
    }

and then in your XAML

      <Style.Triggers>
        <DataTrigger Binding=”{Binding CloseSignal}” Value=”true”>
          <Setter Property=”Behaviours:WindowCloseBehaviour.Close” Value=”true” />
        </DataTrigger> 
    </Style>