How to set selected item of a DataGrid programmatically in WPF with MVVM application?

后端 未结 5 1476
滥情空心
滥情空心 2021-01-02 11:17

I have bound the DataTable to the DataGrid control. How can I set the selected item programmatically ?

Exam

5条回答
  •  自闭症患者
    2021-01-02 11:32

    For anyone using Observable Collections you may find this solution useful.

    The SelectedModelIndex property simply returns the index of the SelectedModel from the ItemSource collection. I've found setting the SelectedIndex along with the SelectedItem highlights the row in the DataGrid.

        private ObservableCollection _itemSource
        public ObservableCollection ItemSource
        {
            get { return _itemSource; }
            set 
            { 
                _itemSource = value; 
                OnPropertyChanged("ItemSource"); 
            }
        }
    
        // Binding must be set to One-Way for read-only properties
        public int SelectedModelIndex
        {
            get 
            {
                if (ItemSource != null && ItemSource.Count > 0)
                    return ItemSource.IndexOf(SelectedModel);
                else
                    return -1;
            }            
        }
    
        private Model _selectedModel;
        public Model SelectedModel
        {
            get { return _selectedModel; }
            set 
            {
                _selectedModel = value;
                OnPropertyChanged("SelectedModel"); 
                OnPropertyChanged("SelectedModelIndex");               
            }                
        }
    

提交回复
热议问题