ScrollIntoView for WPF DataGrid (MVVM)

前端 未结 4 1160
花落未央
花落未央 2020-12-03 07:44

I\'m using the MVVM pattern, and I\'ve created a binding in XAML for the SelectedItem of a DataGrid. I programatically set the SelectedItem, however when I do so the DataGri

4条回答
  •  Happy的楠姐
    2020-12-03 08:22

    This is my solution to get ScrollIntoView working. I perform the operation in the LayoutUpdated() event

    public void ManipulateData()
    {
        // Add a new record or what else is needed;
        myItemsSourceCollection.Add(...); 
    
        // Not needed when the ItemsSource is a ObervableCollectin 
        // with correct Binding (ItemsSource="{ Binding myItemsSourceElement }")
        myDataGrid.Items.Refresh();
    
        // Goto last Item or where ever
        myDataGrid.SelectedIndex = this.myDataGrid.Items.Count - 1;
    }
    
    // The LayoutUpdated event for the DataGrid
    private void myDataGrid_LayoutUpdated(object sender, EventArgs e)
    {
        if (myDataGrid.SelectedItem == null)
            return;
        //<----------
    
        // may become improved to check first if the `ScrollIntoView()` is really needed
    
        // To prevent hanging here the ItemsSource must be 
        // a) an ObervableCollection with a correct working binding or
        // b) myDataGrid.Items.Refresh(); must be called after changing
        // the data
        myDataGrid.ScrollIntoView(myDataGrid.SelectedItem, null);
    }
    

提交回复
热议问题