我的MainWindow中有一个CheckBox
,它可以作为一个切换来打开和关闭另一个窗口(比方说NextWindow)。简单地说,直到现在我所做的是:
CheckBox
时,会打开另一个窗口CheckBox
时,会关闭已打开的窗口现在我想要的是当用户手动关闭NextWindow时更改CheckBox
状态。我需要做什么?
这是我的代码:
对于MainWindow.XAML
<Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="100" Width="100">
<Grid>
<CheckBox Name="chk" Checked="chk_Checked_1" Unchecked="chk_Unchecked_1" Margin="20">Window</CheckBox>
</Grid>
对于MainWindow.xaml.cs
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void chk_Checked_1(object sender, RoutedEventArgs e)
{
NextWindow nw = new NextWindow();
nw.Show();
}
private void chk_Unchecked_1(object sender, RoutedEventArgs e)
{
var window = IsWindowOpen<Window>("Next");
if (window != null)
{
window.Close();
}
}
public static T IsWindowOpen<T>(string name = null)
where T : Window
{
var windows = Application.Current.Windows.OfType<T>();
return string.IsNullOrEmpty(name) ? windows.FirstOrDefault() : windows.FirstOrDefault(w => w.Name.Equals(name));
}
}
对于NextWindow.xaml
<Window x:Class="WpfApplication2.NextWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="NextWindow" Height="100" Width="100" Name="Next">
<Grid>
<Label Margin="20">Hello</Label>
</Grid>
答案 0 :(得分:1)
好的,我按照评论中建议的this link对我的代码进行了以下更改:
主窗口
private void chk_Checked_1(object sender, RoutedEventArgs e)
{
NextWindow nw = new NextWindow();
nw.Closed += nw_Closed;
nw.Show();
}
void nw_Closed(object sender, EventArgs e)
{
chk.IsChecked = false;
}
答案 1 :(得分:0)
只需更改uncheck事件处理程序:
private void chk_Unchecked_1(object sender, RoutedEventArgs e)
{
var window = IsWindowOpen<Window>("Next");
if (window != null)
{
window.Close();
((CheckBox)sender).IsChecked = false;
}
}