Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF Window Closed Event Usage

Tags:

c#

events

wpf

I have a Window class (e.g. public partial class Foo : Window), and when I create the window I sign up for the Closed event as such.

foo = new Foo();
foo.Closed += FooClosed;


public void FooClosed(object sender, System.EventArgs e)
{
}

When someone presses a button inside the foo Window I call this.Close() but my FooClosed doesn't seem to be called.

Am I incorrectly signing up for the event?

Update

By the way, all I'm trying to accomplish is know when foo has been closed so I can set the reference back to null. Is there a better way to accomplish that?

like image 205
Ternary Avatar asked Dec 21 '22 23:12

Ternary


1 Answers

Question was answered a few days ago check Execute code when a WPF closes

You may have something going on with your code because this works just fine for me.

MainWindow.xaml.cs

namespace WpfApplication1
{

    public partial class MainWindow : Window
    {
        private Foo foo;

        public MainWindow()
        {
            InitializeComponent();

            foo = new Foo();
            foo.Closed += FooClosed;
            foo.Show();
        }

        public void FooClosed(object sender, System.EventArgs e)
        {
            //This gets fired off
            foo = null;
        }

    }
}

Foo.xaml

<Window x:Class="WpfApplication1.Foo"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Foo" Height="300" Width="300">
    <Grid>
        <Button Click="Button_Click">Close</Button>
    </Grid>
</Window>

Foo.xaml.cs

namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for Foo.xaml
    /// </summary>
    public partial class Foo : Window
    {
        public Foo()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }
    }
}
like image 68
Dan P Avatar answered Dec 23 '22 12:12

Dan P