我有一个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;
)。
我想这在代码隐藏我的用户,但无济于事(由其他几个StackOverflow的答案建议)(parentWindow
总是空):
var parentWindow = Window.GetWindow(this);
parentWindow.Close();
如果parentWindow是Windows代码它应该管用。如果您使用的是MVVM,则可能需要先由Windows拥有者进行分配。 –
注意:这个问题的最后一部分看起来不再是真实的:在接受的答案下面的评论指出,问题是通过使用这个解决方案(简称:Window.GetWindow(this).Close();')来解决的 – Kjartan