WPF DataGrid不会显示List<>

时间:2016-12-28 20:06:16

标签: c# wpf datagrid

我的DataGrid不会显示任何内容,但我的绑定类包含一行数据。如您所见,我的MockSnifferSource类派生自List,它应该满足我的集合基于IList的要求。

<Window x:Class="WpfSniffer.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:WpfSniffer"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <DataGrid x:Name="dataGrid" Height="Auto" Width="Auto" 
              HorizontalAlignment="Stretch" Margin="0" VerticalAlignment="Stretch"
              ItemsSource="{Binding}" AutoGenerateColumns="True">
        <DataGrid.DataContext>
            <local:MockSnifferSource/>
        </DataGrid.DataContext>
    </DataGrid>
</Grid>

public class MockSnifferSource : List<SnifferMessage>
{
    public MockSnifferSource()
    {
        Add(new SnifferMessage
        { Node = "One", Command = 1, Time = DateTime.Now, Payload = "12345", Metadata = "TTD=5" });
    }
}

public struct SnifferMessage
{ 
    public string Node;
    public byte Command;
    public DateTime Time;
    public string Payload;
    public string Metadata;                          
}

任何人都可以找出问题的根源吗?

1 个答案:

答案 0 :(得分:0)

正如Ed Plunkett所说,你需要properties代替fields以便绑定工作

 public class SnifferMessage
{
    public string Node {get; set; }
    public byte Command { get; set; }
    public DateTime Time { get; set; }
    public string Payload { get; set; }
    public string Metadata { get; set; }
}

其次,我强烈建议使用集合ObservableCollection中的内置版本。这将使您的UI反映更改,如果您的集合每次更改。以下是首选实现

<Window.DataContext>
    <local:MainViewModel/>
</Window.DataContext>

<DataGrid ItemsSource="{Binding SniffMessage}"/>


 public class MainViewModel
{
    public MainViewModel()
    {
        SniffMessage = new ObservableCollection<SnifferMessage>();
        SniffMessage.Add(new SnifferMessage
                { Node = "one", Command = 1, Time = DateTime.Now, Payload = "1234", Metadata = "TTD" }
        );   

    }

    public ObservableCollection<SnifferMessage> SniffMessage { get; set; }

}