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

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

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

Exam

5条回答
  •  -上瘾入骨i
    2021-01-02 11:27

    I just had the same problem. I saw that the item of a datagrid was selected correctly at design time, but not at runtime. (By the way, I create the instance of the view model in the xaml).

    I could solve this problem by moving the code to programmatically set the selected item from the view models constructor to a different method in the view model and then calling this method in the loaded event of the window (or usercontrol).

    Obviously the view is not completely done initializing itself when the view models constructor is called. This can be avoided by not coding in the view models constructor.

    View (xaml):

    
        
            
        
    

    View (code behind):

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            ((ExampleViewModel)this.DataContext).LoadData();
        }
    

    If you do not like setting up the Loaded event in the code behind, you can also do it in xaml (references to "Microsoft.Expression.Interactions" and "System.Windows.Interactivity" are needed):

        
        
            
        
        
            
                
            
        
    

    In each case, you call the LoadData method in the ViewModel:

    public class ExampleViewModel
    {
        /// 
        /// Constructor.
        /// 
        public ExampleViewModel()
        {
            // Do NOT set selected item here
        }
    
    
        public void LoadData()
        {
            // Set selected item here
        }
    

提交回复
热议问题