mercredi 3 février 2016

checkbox state change when window closes

I have a CheckBox in my MainWindow which acts as a toggle to open and close a another window (lets say NextWindow). Putting it simply what I have done up until now is that:

  • When CheckBox is checked, another window opens
  • When CheckBox is unchecked, it closes the opened window

What I want now is to change the CheckBox state, when the NextWindow is manually closed by the user. What do I need to do?
Here are my code:

For MainWindow.XAML

<Window x:Class="WpfApplication2.MainWindow"
    xmlns="http://ift.tt/o66D3f"
    xmlns:x="http://ift.tt/mPTqtT"
    Title="MainWindow" Height="100" Width="100">
<Grid>
    <CheckBox Name="chk" Checked="chk_Checked_1" Unchecked="chk_Unchecked_1" Margin="20">Window</CheckBox>
</Grid>

For 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));
    }
}

For NextWindow.xaml

<Window x:Class="WpfApplication2.NextWindow"
    xmlns="http://ift.tt/o66D3f"
    xmlns:x="http://ift.tt/mPTqtT"
    Title="NextWindow" Height="100" Width="100" Name="Next">
<Grid>
    <Label Margin="20">Hello</Label>
</Grid>




Aucun commentaire:

Enregistrer un commentaire