如何以编程方式在WPF DataGrid中选择行或单元格? [英] How to select a row or a cell in WPF DataGrid programmatically?

查看:551
本文介绍了如何以编程方式在WPF DataGrid中选择行或单元格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在WinForm DataGridView中,它会在初始化时自动选择第一行。当我试图关闭该功能时,它开启了我的疯狂。移动到WPF DataGrid,似乎微软决定关闭这个功能,这是一件好事。但是,我很难现在启用此功能。对于某些DataGrid,我希望在通过数据绑定填充网格后自动选择第一行。互联网上有一些建议,但是我不能做这个工作。我希望在这里更好的运气。

解决方案

设置 IsSynchronizedWithCurrentItem =true b
$ b

编辑:



为了解决您的评论,我假设您的DataGrid的SelectionUnit设置为单元格, 是吗?好的,我不知道这是否是最好的解决方案,但您可以做的一件事是处理DataGrid的Loaded事件,并手动设置代码隐藏中选定的单元格。所以你会有这样的:

 < DataGrid x:Name =dgAutoGenerateColumns =FalseIsSynchronizedWithCurrentItem = True
SelectedCellsChanged =dg_SelectedCellsChangedSelectionUnit =Cell
Loaded =dg_Loaded>
...
< / DataGrid>

事件处理程序:

  private void dg_Loaded(object sender,RoutedEventArgs e)
{
if((dg.Items.Count> 0)&&b $ b(dg.Columns .Count> 0))
{
//选择第一个项目的第一列。
dg.CurrentCell = new DataGridCellInfo(dg.Items [0],dg.Columns [0]);
dg.SelectedCells.Add(dg.CurrentCell);
}
}

请注意,只有在DataGrid.SelectionUnit设置为单元格。否则我相信会抛出一个例外。



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 =MainWindowHeight =350 Width =525>
< StackPanel>
< Button Click =Button_Click>重设< / Button>
< DataGrid x:Name =dgAutoGenerateColumns =FalseIsSynchronizedWithCurrentItem =True
SelectionUnit =Cell
DataContextChanged =dg_DataContextChanged
ItemsSource ={绑定项目}
Loaded =dg_Loaded>
< DataGrid.Columns>
< DataGridTextColumn Binding ={Binding}/>
< /DataGrid.Columns>
< / DataGrid>
< / StackPanel>
< / Window>

代码背后:

 命名空间WpfApplication1 
{
///< summary>
/// 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)&&b $ b(dg.Columns .Count> 0))
{
//选择第一个项目的第一列。
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();
}
}
}


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 Microsoft has decided to turn this feature off, which is a good thing I think. However, I have hard time to enable this feature now. For some DataGrid, I want the first row to be selected automatically after grid is populated through data binding. There are some suggestions in Internet, but I couldn't make that work. I hope for better luck here.

解决方案

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:

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

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:

<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>

Code-Behind:

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

这篇关于如何以编程方式在WPF DataGrid中选择行或单元格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆