gpt4 book ai didi

c# - 如何以编程方式选择 WPF DataGrid 中的行或单元格?

转载 作者:太空狗 更新时间:2023-10-29 17:42:37 25 4
gpt4 key购买 nike

在WinForm DataGridView中,初始化时会自动选择第一行。当我试图关闭该功能时,它把我逼疯了。转向 WPF DataGrid,Microsoft 似乎决定关闭此功能,我认为这是一件好事。但是,我现在很难启用此功能。对于某些 DataGrid,我希望在通过数据绑定(bind)填充网格后自动选择第一行。互联网上有一些建议,但我做不到。我希望在这里好运。

最佳答案

设置 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”时有效。否则,我相信它会抛出异常。

编辑 2:

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

关于c# - 如何以编程方式选择 WPF DataGrid 中的行或单元格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3836191/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com