2016-12-28 20 views
-1

我的DataGrid不會顯示任何內容,但我的綁定類包含一行數據。正如你所看到的,我的MockSnifferSource類是從List派生的,它應該滿足我的集合基於IList的需求。WPF DataGrid將不會顯示列表<>

<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

首先,不要用'List',使用'ObservableCollection'。但這不是你的問題。您的問題可能在嘗試綁定到字段。你不能。 'SnifferMessage'應該有屬性,而不是字段:'public string Node {get;組;最後,它看起來像你的集合是你的DataContext。這不是一個好主意;你只需稍後修復它。給你的viewmodel一個集合屬性並綁定到它。 –

+0

謝謝。在我看到帖子之前就想到了這一點,傻了我。花了我一段時間來弄清楚什麼是視圖模型,但是它在下面的例子中,並且它工作。 – Cormagh

+0

太好了。你應該接受他的回答。 –

回答

0

愛德賓吉說,你需要有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使用的版本。這會讓你的用戶界面反映變化,如果你的收藏每改變一次。下面是首選的實施

<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; } 

} 
+0

感謝您的解決方案。我完全錯過了因爲生鏽而需要屬性的事實,並且我讚賞地將之前使用過的ObservableCollection進行了升級。 – Cormagh