【问题标题】:C# WPF Populating datagrid with listC# WPF 用列表填充数据网格
【发布时间】:2020-11-17 18:57:09
【问题描述】:

我编写了这段代码,它循环循环,每次迭代都重新创建一个新列表。目标是在每次迭代时在数据网格中显示刷新的列表(应该每 1 秒左右发生一次)。

我认为我在 xaml 中的命名或绑定某处犯了一个错误,因为我的理解是数据网格应该自动填充返回的列表,但目前它什么都不做并且保持空白 - 我该怎么做数据网格填充列表?

迭代的代码是这样的:

int i = 0;
do
{
    i += 1;
    UDPDataGrid.ItemsSource = LoadTimestamp(i);
    UDPDataGrid.Items.Refresh();
} while (FinalExit == false);

LoadTimestamp 传递参数 i,并返回一个列表,如以下缩短的 sn-p 中所总结的:

private List<RowEntry> LoadTimestamp(int i)
{
    // Initialise datagroup
    List<RowEntry> TimestampGroup = new List<RowEntry>();

    // Set port receiving
    UdpClient receivingUdpClient = new UdpClient(int.Parse(txtPort.Text));
    IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);

    ....................
    ....................
    ....................

    return TimestampGroup;
}

最后,我在 window.xaml 文件中有如下条目:

<Window x:Class="UDP_Receiver.MainWindow"
..........
Title="UDP Receiver" Height="750" Width="1200">
..........    
<Grid Margin="0,0,16,34">
<DataGrid Name="UDPDataGrid" ItemsSource="{Binding TimestampGroup}" HorizontalAlignment="Left" Height="300" Margin="29,55,0,0" VerticalAlignment="Top" Width="1107"/>
</Grid>
</Window>

【问题讨论】:

  • do-while 循环运行时,什么都不会起作用,因为它阻止了应用程序的工作(尝试拖动应用程序的窗口进行测试)。请改用Task.Run()Timerasync-await。循环在哪里?你能显示完整的LoadTimestamp 代码吗?
  • 注意:ItemsSource="{Binding TimestampGroup}"UDPDataGrid.ItemsSource = LoadTimestamp(i) 是互斥操作。选择一个:Binding+ObservableCollection 形成答案,或ItemsSource =List。或者最好了解一下INotifyPropertyChanged 及其实现。我理解这个问题,但无法回答这个问题,因为它需要更多的细节和清晰度以及更多的代码来重现问题。

标签: c# data-binding binding datagrid


【解决方案1】:

你必须使用 ObservableCollection,类似的东西

        int i = 0;
        do
        {
            i += 1;
            LoadTimestamp(int i);
        } while (FinalExit == false);


    public ObservableCollecation<RowEntry> TimestampGroup {set; get;} = new ObservableCollecation<RowEntry>();
    
    private void LoadTimestamp(int i)
    {
        TimestampGroup.Clear();

        // Set port receiving
        UdpClient receivingUdpClient = new UdpClient(int.Parse(txtPort.Text));
        IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);

        // Update collection TimestampGroup here
    }

【讨论】:

  • 我的代码基于这篇文章:c-sharpcorner.com/UploadFile/mahesh/datagrid-in-wpf 不使用 observablecollection?
  • 而且你的方法行不通。它仅在您初始化集合一次时才有效。如果您需要在广播中更改它,您应该使用 ObservableCollection。
  • ObservableCollection 仅在您添加/删除行时提供 UI 刷新,而不强制 DataGrid 刷新其布局。分配ItemsSource 是可以的。但是OP的问题不在此范围内。问题是冻结的应用程序,因为do-while 循环阻塞了主 UI 线程。因此,这个答案很有用,但无济于事。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-19
  • 2011-06-15
  • 1970-01-01
  • 2013-11-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多