Search code examples
.netxamluser-controls

How to close dialog window from inside UserControl


I have a UserControl that has a cancel and ok button. Like e.g. the Wizard control in the wpf extended toolkit.

How can I close the window using this control, when the user clicks cancel or ok in the UserControl?

I can't set DialogResult = true in the OnOk handler, because my control is not a window. Do I have to go up the visual tree in order to find the window, or is there a better solution?

The control:

<UserControl x:Class="WizardTest.WizardControl"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         mc:Ignorable="d" 
         d:DesignHeight="300" d:DesignWidth="300">
<DockPanel>
    <UniformGrid DockPanel.Dock="Bottom" Columns="2">
        <Button Click="OnCancel">Cancel</Button>
        <Button Click="OnOk">Finish</Button>
    </UniformGrid>
</DockPanel>


Solution

  • You'll need to get at the active Window:

    var w = Application.Current.Windows.OfType<Window>().SingleOrDefault(x => x.IsActive);
    if (w == null) { return; }
    
    w.Close();