How to select a row or a cell in WPF DataGrid programmatically?

后端 未结 4 1304
臣服心动
臣服心动 2021-01-11 16:55

In WinForm DataGridView, it automatically selects the first row when initialized. It drove me crazy when I tried to turn that feature off. Moving to WPF DataGrid, it seems M

4条回答
  •  心在旅途
    2021-01-11 17:49

    Set IsSynchronizedWithCurrentItem = "true".

    EDIT:

    To address your comment, I assume that your DataGrid's SelectionUnit is set to "Cell", is it? Okay, I'm not sure if this is the best solution but one thing you can do is handle the Loaded event for the DataGrid and manually set the selected cell in the code-behind. So you'll have something like this:

    
        ...
    
    

    Event-Handler:

    private void dg_Loaded(object sender, RoutedEventArgs e)
    {
        if ((dg.Items.Count > 0) &&
            (dg.Columns.Count > 0))
        {
            //Select the first column of the first item.
            dg.CurrentCell = new DataGridCellInfo(dg.Items[0], dg.Columns[0]);
            dg.SelectedCells.Add(dg.CurrentCell);
        }
    }
    

    Note that this will only work if the DataGrid.SelectionUnit is set to "Cell". Otherwise, I believe it will throw an exception.

    EDIT2:

    XAML:

    
        
            
            
                
                    
                
            
        
    
    

    Code-Behind:

    namespace WpfApplication1
    {
        /// 
        /// Interaction logic for MainWindow.xaml
        /// 
        public partial class MainWindow : Window
        {
            public MainWindow()
            {
                InitializeComponent();
                this.LoadItems();
            }
    
            private void Button_Click(object sender, RoutedEventArgs e)
            {
                this.LoadItems();
            }
    
            private void LoadItems()
            {
                this.DataContext = new { Items = new List { "Item1", "Item2", "Item3" } };
                this.SelectFirstItem();
            }
    
            private void dg_Loaded(object sender, RoutedEventArgs e)
            {
                SelectFirstItem();
            }
    
            void SelectFirstItem()
            {
                if ((dg.Items.Count > 0) &&
                    (dg.Columns.Count > 0))
                {
                    //Select the first column of the first item.
                    dg.CurrentCell = new DataGridCellInfo(dg.Items[0], dg.Columns[0]);
                    dg.SelectedCells.Add(dg.CurrentCell);
                }
            }
    
            private void dg_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
            {
                this.SelectFirstItem();
            }
        }
    }
    

提交回复
热议问题