如何从用户控件里面关闭一个窗口?

时间:2016-05-12 12:48:59

标签: c# wpf user-controls

我有一个WPF程序,在某些时候我打开一个窗口:

    public object testCommand()
    {
        Window window = new Window
        {
            Title = "My User Control Dialog",
            Content = new OKMessageBox("Error Message"),
            SizeToContent = SizeToContent.WidthAndHeight,
            ResizeMode = ResizeMode.NoResize
        };
        window.WindowStartupLocation = WindowStartupLocation.CenterScreen;
        window.ShowDialog();

        return null;
    }

用户控制XAML:

<UserControl x:Class="SolidX.Base.MessageBoxes.OKMessageBox"
             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" 
             xmlns:local="clr-namespace:SolidX.Base.MessageBoxes"
             xmlns:viewProperties="clr-namespace:AppResources.Properties;assembly=AppResources"
             mc:Ignorable="d" 
             d:DesignHeight="150" d:DesignWidth="400">
    <Grid>
        <TextBlock x:Name="textMessage" Margin="10"/>
        <Grid Height="Auto" VerticalAlignment="Bottom">
            <Grid.RowDefinitions>
                <RowDefinition/>
                <RowDefinition/>
            </Grid.RowDefinitions>
            <CheckBox Content="Don't show this again" HorizontalAlignment="Right" Margin="5,5,10,5"/>
            <StackPanel Grid.Row="1" Orientation="Horizontal" HorizontalAlignment="Right">
                <Button x:Name="btnOk" Content="{x:Static viewProperties:Resources.Common_OK}" Height="25" VerticalAlignment="Center" Width="90" Margin="5"/>
            </StackPanel>
        </Grid>
    </Grid>
</UserControl>

用户控制代码隐藏:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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;

namespace SolidX.Base.MessageBoxes
{
    /// <summary>
    /// Interaction logic for OKMessageBox.xaml
    /// </summary>
    public partial class OKMessageBox : UserControl
    {
        public OKMessageBox(string Message)
        {
            InitializeComponent();
            textMessage.Text= Message;
        }
    }
}

在我的用户控件中,我正在尝试关闭窗口的按钮(目前设置Button.IsCancel = true;有效,但我希望这是一个可重用的选项 - 基本上是我自己的this.Close;

我在我的usercontrol的代码隐藏中尝试了这个(正如其他几个StackOverflow答案所建议的那样),但是没有用(parentWindow总是为null):

var parentWindow = Window.GetWindow(this);
parentWindow.Close();

4 个答案:

答案 0 :(得分:4)

在UserControl中尝试:

XAML

<UserControl .... Loaded="UserControl_Loaded">
    <!--  -->
</UserControl>

CS

public UserControl()
{
    InitializeComponent();
}

private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
    var window = Window.GetWindow(this);
    window.Close();
}

答案 1 :(得分:0)

如果您为Window使用ViewModel类,可以将ViewModel类设置为Window实例,ViewModel可以存储它的所有者。

例如ViewModel:

public class CloseConfirmViewModel
{
    internal Window Owner { get; set; }

    public ICommand CloseCommand { get; private set; } // ICommand to bind it to a Button

    public CloseConfirmViewModel()
    {
        CloseCommand = new RelayCommand<object>(Close);
    }

    public void Close() // You can make it public in order to call it from codebehind
    {
        if (Owner == null)
            return;

        Owner.Close();
    }
}

为了使其正常工作,您必须将ViewModel类设置为Window

public partial class CloseConfirmWindow : Window
{
    public CloseConfirmWindow(CloseConfirmViewModel model)
    {
        DataContext = model;

        InitializeComponent();

        model.Owner = this;
    }
}

您正在以这种方式创建一个新实例:

var model = new CloseConfirmViewModel();
var closeWindow = new CloseConfirmWindow(model);
closeWindow.ShowDialog(); // Hopefully you've added a button which has the ICommand binded

您可以通过这种方式将Window CloseCommand绑定到UserControl按钮,或者如果您没有使用命令,请拨打{{ 1}}点击UC按钮时的方法。

答案 2 :(得分:0)

这些方法都不适合我。大多数人只是关闭了父窗口。我从主窗口使用XAML弹出窗口。像

<DockPanel/>
   <Popup x:Name="puMyControl"/>
      <Local:UserControl />
   </Popup>
</DockPanel>

在我的主窗口后面的其他地方,我添加了:

puMyControl.IsOpen = true;

在UserControl内部,我有一个取消按钮。弹出窗口没有孩子,因此我需要引用弹出窗口的父对象DockPanel。

private void BtnClose_Click(object sender, RoutedEventArgs e)
{
    Popup pu = Parent as Popup;
    if ( pu != null )
    {
       DockPanel dp = pu.Parent as DockPanel;
       if (dp != null)
       {
          dp.Children.Remove(pu);
       }
    }
}

啊哈的时刻是,我要删除弹出窗口,而不是UserControl。 'this'指的是UserControl。如您在上面看到的,我正在从DockPanel中删除弹出窗口。这导致了一个更简单,更通用的解决方案。

Popup pu = Parent as Popup;
if (pu != null)
{
   pu.IsOpen = false;
}

答案 3 :(得分:-1)

要关闭模态对话框,您应设置DialogResult: var data = [{ label: 'red', color: 'red', data: 1, radius: 100 // radius in pixel (about 50% here) }, { label: 'green', color: 'green', data: 3 // default is the general radius }, { label: 'blue', color: 'blue', data: 2, radius: 0.8 // radius 80% of general radius (about 160 pixel here) }];