gpt4 book ai didi

c# - 在 WPF 中使用计时器刷新数据网格后如何将我的选择保留到 DataGrid 行

转载 作者:太空宇宙 更新时间:2023-11-03 13:38:50 26 4
gpt4 key购买 nike

我有 WPF DataGrid,我正在绑定(bind) DataGrid,但如果对数据进行任何更改,它将自动刷新,但我对数据网格行的选择将取消选择。

最佳答案

不要使用 List 来存储数据,请尝试使用 ObservableCollection。使用 ObservableCollection 的优势在于,无论何时向集合添加项目,UI 都会自动更新,因此不需要手动刷新 DataGrid。下面我分享了一个示例应用程序,它在 DataGrid 中添加和更新记录。

XAML:

<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<StackPanel Orientation="Horizontal">
<RadioButton Name="CBAdd" GroupName="AddOrEdit" Content="Add Messages" IsChecked="True"></RadioButton>
<RadioButton Name="CBUpdate" GroupName="AddOrEdit" Content="Update Messages"></RadioButton>
</StackPanel>
<DataGrid Grid.Row="1" Name="DGNew" CanUserAddRows="False">

</DataGrid>
</Grid>

代码隐藏:

using System;
using System.Windows;
using System.Timers;
using System.Collections.ObjectModel;
using System.Windows.Threading;
using System.ComponentModel;

namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
Timer _timer = null;
ObservableCollection<CustomMessage> _messages = null;

int count = 0;

public MainWindow()
{
InitializeComponent();
_messages = new ObservableCollection<CustomMessage>();
count++;
_messages.Add(new CustomMessage() { ID = count, Message = "Message" });
_timer = new Timer(1000);
_timer.Elapsed += new ElapsedEventHandler(_timer_Elapsed);

this.DGNew.ItemsSource = _messages;
_timer.Start();
}

void _timer_Elapsed(object sender, ElapsedEventArgs e)
{
try
{
_timer.Stop();
Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, new Action(() =>
{
if (this.CBAdd.IsChecked == true)
{
count++;
_messages.Add(new CustomMessage() { ID = count, Message = "Timer Message " + count });
}
else
{
// Udpate existing Message
Random random = new Random();
CustomMessage message = _messages[random.Next(0, count)];
message.Message = "Updated Time" + DateTime.Now.ToLongTimeString();
}
}));
}
finally
{
_timer.Start();
}
}
}

public class CustomMessage : INotifyPropertyChanged
{
private int _ID;

public int ID
{
get { return _ID; }
set
{
_ID = value;
OnPropertyChanged("ID");
}
}

private string _Message;

public string Message
{
get { return _Message; }
set
{
_Message = value;
OnPropertyChanged("Message");
}
}

public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}

关于c# - 在 WPF 中使用计时器刷新数据网格后如何将我的选择保留到 DataGrid 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17825368/

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