Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF Toolkit DataGrid column resize event

I am using WPF Toolkit Datagrid in one of the applications I am working on. What I want is to store the column width and displayindex as a user preference. I have achived it for column displayindex but for resize I could not find any event on the datagrid which will trigger after column size change. I have tried the "SizeChanged" event which I guess is only fired when it is initially calculating the size and that too is for the whole datagrid and not for the individual columns.
Any alternate solution or if anybody knows about the event ?

like image 528
Pravin Avatar asked Oct 25 '10 15:10

Pravin


2 Answers

taken from... :

http://forums.silverlight.net/post/602788.aspx

after load :

    PropertyDescriptor pd = DependencyPropertyDescriptor
                             .FromProperty(DataGridColumn.ActualWidthProperty,
                                           typeof(DataGridColumn));

        foreach (DataGridColumn column in Columns) {
                //Add a listener for this column's width
                pd.AddValueChanged(column, 
                                   new EventHandler(ColumnWidthPropertyChanged));
        }

2 methods:

    private bool _columnWidthChanging;
    private bool _handlerAdded;
    private void ColumnWidthPropertyChanged(object sender, EventArgs e)
    {
        // listen for when the mouse is released
        _columnWidthChanging = true;
        if (!_handlerAdded && sender != null)
        {
            _handlerAdded = true;  /* only add this once */
            Mouse.AddPreviewMouseUpHandler(this, BaseDataGrid_MouseLeftButtonUp);
        }
    }

    void BaseDataGrid_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
    {
        if (_columnWidthChanging) {
            _columnWidthChanging = false;
          // save settings, etc

        }

        if(_handlerAdded)  /* remove the handler we added earlier */
        {
             _handlerAdded = false;
             Mouse.RemovePreviewMouseUpHandler(this, BaseDataGrid_MouseLeftButtonUp);
        }
    }

The ColumnWidthPropertyChanged fires constantly while the user drags the width around. Adding the PreviewMouseUp handler lets you process when the user is done.

like image 189
J... Avatar answered Nov 11 '22 22:11

J...


LayoutUpdated?

I'm working in Silverlight, and the grid is rebound/refreshed every second.

I'm using the LayoutUpdated method, which fires for every layout updating event.

You could keep a dictionary of the column widths and check for deltas. Then you would know which column(s) had changed.

foreach (DataGridColumn column in dataGrid1.Columns)
{
    // check for changes...
    // save the column.Width property to a dictionary...
}
like image 1
arachnode.net Avatar answered Nov 11 '22 21:11

arachnode.net