locked
Best Place to Call DependencyPropertyDescriptor RemoveValueChanged RRS feed

  • Question

  • Hello,

    I'm extending WPF's DataGrid. In my OnInitialize method, I register a couple of event handlers on each of the grid's columns using DependencyPropertyDescriptor AddValueChanged. What is the best-practice way to remove these handlers when my custom DataGrid is no longer needed? Is the approach I'm used (see below) good or is there a better way?

    Right now, my code looks like this:

            protected override void OnInitialized(EventArgs e)
            {
                base.OnInitialized(e);
    
                EventHandler sortDirectionChangedHandler = (sender, x) => doSomething();
                EventHandler widthPropertyChangedHandler = (sender, x) => doSomethingElse();
                var sortDirectionPropertyDescriptor = DependencyPropertyDescriptor.FromProperty(DataGridColumn.SortDirectionProperty, typeof(DataGridColumn));
                var widthPropertyDescriptor = DependencyPropertyDescriptor.FromProperty(DataGridColumn.WidthProperty, typeof(DataGridColumn));
    
                Loaded += (sender, t) =>
                {
                    foreach (var column in Columns)
                    {
                        sortDirectionPropertyDescriptor.AddValueChanged(column, sortDirectionChangedHandler);
                        widthPropertyDescriptor.AddValueChanged(column, widthPropertyChangedHandler);
                    }
                };
                Unloaded += (sender, t) =>
                {
                    foreach (var column in Columns)
                    {
                        sortDirectionPropertyDescriptor.RemoveValueChanged(column, sortDirectionChangedHandler);
                        widthPropertyDescriptor.RemoveValueChanged(column, widthPropertyChangedHandler);
                    }
                };
            }

    If my custom DataGrid is displayed in a child window, Unloaded will be called when that window is closed. Unloaded is not called when the application shuts down. I don't think that this is a problem because all memory used by my application is cleaned up when it closes, so the fact that these events have not been unregistered is irrelevant.

    Thank you,
    Ben

     

    Thursday, March 8, 2012 9:55 PM

Answers

  • You are correct in that when app goes down it doesn't matter anylonger.  I think your code looks perfect and will work without problem.

    JP Cowboy Coders Unite!

    • Proposed as answer by Sheldon _Xiao Saturday, March 10, 2012 7:29 AM
    • Marked as answer by Ben Gribaudo Monday, March 12, 2012 2:55 PM
    Thursday, March 8, 2012 11:46 PM