如何将列表正确绑定到WPF DataGrid

l46*_*kok 0 .net c# wpf xaml datagrid

我正在尝试使用ItemSource将列表绑定到数据网格:

xaml.cs

<UserControl x:Class="DDCUI.CommDiagnosisWPFCtrl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" Height="800" Width="300">
    <DockPanel>
        <DataGrid DockPanel.Dock="Top" Height="300" AutoGenerateColumns="True" Name="DGComm" CanUserResizeColumns="True" IsReadOnly="True" ItemsSource="{Binding Source=dataGridRows}">
            <DataGrid.Columns>
                <DataGridTextColumn Header="No." Binding="{Binding Number}" Width="0.1*"/>
                <DataGridTextColumn Header="Time" Binding="{Binding Time}" Width="0.1*" />
                <DataGridTextColumn Header="Protocol" Binding="{Binding Protocol}" Width="0.15*" />
                <DataGridTextColumn Header="Source" Binding="{Binding Source}" Width="0.15*" />
                <DataGridTextColumn Header="Destination" Binding="{Binding Destination}" Width="0.15*" />
                <DataGridTextColumn Header="Data" Binding="{Binding Data}" Width="0.5*" />
            </DataGrid.Columns>
        </DataGrid>
        <RichTextBox DockPanel.Dock="Bottom" Height="150" Name="RtbHexCode"/>
        <TreeView DockPanel.Dock="Bottom" Height="200" Name="TreeViewDecode"/>

    </DockPanel>
</UserControl>
Run Code Online (Sandbox Code Playgroud)

码:

public class CommDGDataSource
{
    public string Number { get; set; }
    public string Time { get; set; }
    public string Protocol { get; set; }
    public string Source { get; set; }
    public string Destination { get; set; }
    public string Data { get; set; }
}

private List<object> dataGridRows = new List<object>();

private void DGAddRow(string name, FunctionType ft)
{
    CommDGDataSource ds = new CommDGDataSource();
    ds.Protocol = name;
    ds.Source = "";
    ds.Destination = "";
    ds.Number = rowCount.ToString();
    ds.Data = "";
    ds.Time = "";
    dataGridRows.Add(ds);
}
Run Code Online (Sandbox Code Playgroud)

调用DGAddRow时,DataGrid不会更新其值.

我在这做错了什么?任何帮助,将不胜感激.

此外,XAML甚至在填充数据之前就预先生成空行.我希望只能显示填充项目的行(并将新行添加到最后一个填充行的底部).我怎么能做到这一点?

Rov*_*ver 6

使用ObservableCollection <>而不是List <>并使dataGridRows公开.

  • 公共和财产. (3认同)