简体   繁体   中英

WPF DataGrid: How do I change the selected row programatically?

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM