WPF Datagrid set selected row

后端 未结 8 1376
无人共我
无人共我 2020-11-27 05:08

How do I use the Datagrid.SelectedItem to select a row programmatically?

Do I first have to create a IEnumerable of DataGridRow

8条回答
  •  心在旅途
    2020-11-27 05:46

    You don't need to iterate through the DataGrid rows, you can achieve your goal with a more simple solution. In order to match your row you can iterate through you collection that was bound to your DataGrid.ItemsSource property then assign this item to you DataGrid.SelectedItem property programmatically, alternatively you can add it to your DataGrid.SelectedItems collection if you want to allow the user to select more than one row. See the code below:

    
    
        
        
        

    public partial class MainWindow : Window
    {
        public class Employee
        {
            public string Code { get; set; }
            public string Name { get; set; }
        }
    
        private ObservableCollection _empCollection;
    
        public MainWindow()
        {
            InitializeComponent();
        }
    
        private void OnWindowLoaded(object sender, RoutedEventArgs e)
        {
            // Generate test data
            _empCollection =
                new ObservableCollection
                    {
                        new Employee {Code = "E001", Name = "Mohammed A. Fadil"},
                        new Employee {Code = "E013", Name = "Ahmed Yousif"},
                        new Employee {Code = "E431", Name = "Jasmin Kamal"},
                    };
    
            /* Set the Window.DataContext, alternatively you can set your
             * DataGrid DataContext property to the employees collection.
             * on the other hand, you you have to bind your DataGrid
             * DataContext property to the DataContext (see the XAML code)
             */
            DataContext = _empCollection;
        }
    
        private void OnSelectionButtonClick(object sender, RoutedEventArgs e)
        {
            /* select the employee that his name matches the
             * name on the TextBox
             */
            var emp = (from i in _empCollection
                       where i.Name == empNameTextBox.Text.Trim()
                       select i).FirstOrDefault();
    
            /* Now, to set the selected item on the DataGrid you just need
             * assign the matched employee to your DataGrid SeletedItem
             * property, alternatively you can add it to your DataGrid
             * SelectedItems collection if you want to allow the user
             * to select more than one row, e.g.:
             *    empDataGrid.SelectedItems.Add(emp);
             */
            if (emp != null)
                empDataGrid.SelectedItem = emp;
        }
    }
    

提交回复
热议问题