1

How do I change the selected row programatically?

I change change the selected item and cell, but I cannot figure out how to get the whole row highlighted.

Note: The highlighting works fine when a user selects a row with mouse or keyboard.

Jonathan Allen
  • 68,373
  • 70
  • 259
  • 447

2 Answers2

0

take a look at this page. You need both the SelectionUnit and SelectionMode to specify how the selection is done in the DataGrid.

With SelectionUnit = FullRow and SelectionMode = Single, the user can only select one row at a time.

edit: after trying it out, it looks as though DataGrid.SelectedItem[i] will select an entire row. Unfortunately, it looks as if you will have to manually set the highlight in an event handler that you have to create for the SelectionChanged property of the DataGrid.

vlad
  • 4,748
  • 2
  • 30
  • 36
  • I already have those settings, the highlighting works fine when a user selects a row with mouse or keyboard. I need to know how to change the selection using code. – Jonathan Allen Oct 01 '10 at 20:44
0

It seems that the SelectedItem only gets picked up after the Loaded event of the containg element (for example UserControl). This seems to work:

 public partial class UserControlClass
{
    public UserControlClass()
    {
        InitializeComponent();

        Loaded += UserControlClass_Loaded;
    }

    void UserControlClass_Loaded(object sender, System.Windows.RoutedEventArgs e)
    {
        if (YourItemsControl.Items.Count > 0)
            YourItemsControl.SelectedItem = YourItemsControl.Items[0];
    }
}

The code above will show the first item selected if YourItemsControl is bound to a collection that has any items in it.

jl.
  • 752
  • 6
  • 19