簡體   English   中英

如何以編程方式在WPF DataGrid中選擇行或單元格?

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

在WinForm DataGridView中,它會在初始化時自動選擇第一行。 當我試圖關掉這個功能時,它讓我抓狂。 轉移到WPF DataGrid,似乎微軟決定關閉這個功能,這是我認為的好事。 但是,我現在很難啟用此功能。 對於某些DataGrid,我希望在通過數據綁定填充網格后自動選擇第一行。 互聯網上有一些建議,但我無法做到這一點。 我希望在這里有更好的運氣。

設置IsSynchronizedWithCurrentItem = "true"

編輯:

為了解決您的評論,我假設您的DataGrid的SelectionUnit設置為“Cell”,是嗎? 好的,我不確定這是否是最好的解決方案,但您可以做的一件事是處理DataGrid的Loaded事件並在代碼隱藏中手動設置選定的單元格。 所以你會有這樣的事情:

<DataGrid x:Name="dg" AutoGenerateColumns="False" IsSynchronizedWithCurrentItem="True"
            SelectedCellsChanged="dg_SelectedCellsChanged" SelectionUnit="Cell"
            Loaded="dg_Loaded">
    ...
</DataGrid>

事件處理程序:

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);
    }
}

請注意,這僅在DataGrid.SelectionUnit設置為“Cell”時才有效。 否則,我相信會拋出異常。

EDIT2:

XAML:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <StackPanel>
        <Button Click="Button_Click">Reset</Button>
        <DataGrid x:Name="dg" AutoGenerateColumns="False" IsSynchronizedWithCurrentItem="True"
                SelectionUnit="Cell"
                DataContextChanged="dg_DataContextChanged"
                ItemsSource="{Binding Items}"
                Loaded="dg_Loaded">
            <DataGrid.Columns>
                <DataGridTextColumn Binding="{Binding}"/>
            </DataGrid.Columns>
        </DataGrid>
    </StackPanel>
</Window>

代碼隱藏:

namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    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<string> { "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();
        }
    }
}

您可以在DataGrid.Loaded事件中一致地執行此操作。 只需獲取第一行並讓行觸發選擇事件。

void MyGridLoaded(...) {
DataGridRow r = yourGrid.ItemContainergenerator.ContainerFromIndex(0) as DataGridRow;
  if(r != null) {
     r.IsSelected = false;
     r.IsSelected = true;
  }

} 

我不確定這是一個錯誤,因為在加載控件之前,可能無法保證您的對象可以觸發選擇事件。 不知道。

你可以試試這個。

        this.dataGrid.SelectionMode = DataGridSelectionMode.Single;

        // Selects the 4th row.
        this.dataGrid.SelectedIndex = 3;

我很高興通過ItemContainerGenerator.StatusChanged事件報告我找到了解決此問題的方法。

dataGrid.ItemContainerGenerator.StatusChanged += new EventHandler(ItemContainerGenerator_StatusChanged);

void ItemContainerGenerator_StatusChanged(object sender, EventArgs e)
        {
            if (dataGrid.ItemContainerGenerator.Status == GeneratorStatus.ContainersGenerated)
            {
                dataGrid.SelectedIndex = 0;
            }
        }

它查看此事件以狀態ContainersGenerated觸發時,dataGrid已完全初始化。 對我來說,這更像是WinForm中DataGridView的DataBindingComplete事件。 如果是這樣,“ DataContextChanged ”事件應該被稱為“ DataContextChanging ”事件。

這是由一個帖子的啟發在這里我無意中發現而尋找另一條線索。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM