gpt4 book ai didi

c# - 以编程方式选择 wpf 数据网格行并突出显示

转载 作者:行者123 更新时间:2023-12-02 04:41:58 25 4
gpt4 key购买 nike

我在 WPF 中创建了一个包含几行的数据网格。我在 wpf 网格上创建了​​四个按钮,以便在行之间导航: [<<] -- [<] -- [>] -- [>>]

我使用 SelectedItem 函数来设置行。我的问题是突出显示看起来很糟糕(很慢)(有点难以解释)。

当我使用键盘箭头(向上和向下)在行之间移动时,突出显示快速且立即。在我的按钮后面的代码中,突出显示有点慢而且奇怪。

这是我的代码

        private void Button_Click_Goto_Premier(object sender, RoutedEventArgs e)
{
myDataGridEvtCode.SelectedItem = myDataGridEvtCode.Items[0];
myDataGridEvtCode.Focus();
}

private void Button_Click_Goto_Precedent(object sender, RoutedEventArgs e)
{
if (myDataGridEvtCode.SelectedIndex > 0)
{
myDataGridEvtCode.SelectedItem = myDataGridEvtCode.Items[myDataGridEvtCode.SelectedIndex - 1];
myDataGridEvtCode.Focus();
}
}

private void Button_Click_Goto_Suivant(object sender, RoutedEventArgs e)
{
if (myDataGridEvtCode.SelectedIndex < myDataGridEvtCode.Items.Count - 1)
{
myDataGridEvtCode.SelectedItem = myDataGridEvtCode.Items[myDataGridEvtCode.SelectedIndex + 1];
myDataGridEvtCode.Focus();
}
}

private void Button_Click_Goto_Dernier(object sender, RoutedEventArgs e)
{
myDataGridEvtCode.SelectedItem = myDataGridEvtCode.Items[myDataGridEvtCode.Items.Count-1];
myDataGridEvtCode.Focus();
}

有人对此有什么想法吗?

非常感谢我的 friend :)

最佳答案

我假设您使用System.Windows.Control.DataGrid。我没有尝试你的代码。下面是一些代码,我只是将它们放在一个示例 WPF 应用程序中。通过按下按钮进行选择与使用鼠标/键盘手动选择行一样流畅。

XAML

<Window x:Class="WpfApplication3.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>
<DataGrid x:Name="MyGrid" Height="200"/>
<Button Content="Previous" Click="Previous"/>
<Button Content="Next" Click="Next"/>
</StackPanel>
</Window>

隐藏代码

namespace WpfApplication3
{
public class Person
{
public Person(string firstName, string lastName)
{
FirstName = firstName;
LastName = lastName;
}

public string FirstName { get; set; }
public string LastName { get; set; }
}

public partial class MainWindow
{
public MainWindow()
{
InitializeComponent();

var persons = new List<Person>
{
new Person("Steve", "Jobs"),
new Person("Bill", "Gates"),
new Person("Dan", "Brown"),
new Person("Barack", "Obama")
};

MyGrid.ItemsSource = persons;
}

private void Next(object sender, RoutedEventArgs e)
{
MyGrid.Focus();

int nextIndex = MyGrid.SelectedIndex + 1;
if (nextIndex > MyGrid.Items.Count - 1) return;
MyGrid.SelectedIndex = nextIndex;
}

private void Previous(object sender, RoutedEventArgs e)
{
MyGrid.Focus();

int previousIndex = MyGrid.SelectedIndex - 1;
if (previousIndex < 0) return;
MyGrid.SelectedIndex = previousIndex;
}
}
}

使用索引可能是线索。虽然我还没有寻找证据。

关于c# - 以编程方式选择 wpf 数据网格行并突出显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15121723/

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