我試圖編程添加項目到WPF中的ListView。我做了大量的閱讀(包括一些問題),並認爲我做得正確,但是項目沒有顯示出來。據我瞭解,我創建ListViewe並將其綁定到數據源,在這種情況下是一個ObservableCollection。我已經驗證ObservableCollection獲取項目添加到它,但它們不會顯示在ListView上。如果它很重要,那麼在我運行LINQ查詢並嘗試向其中添加項目時,ListView已經實例化。動態添加項目到WPF列表視圖
這裏是定義列表視圖中的XAML:
<TabPanel Name="ResultsTab" Height="200" Width ="500" DockPanel.Dock="Top" HorizontalAlignment="Left">
<TabItem Name="Default_Tab" Header="Default">
<ListView Name="DefaultListView" ItemsSource="Binding FCPortCollection">
<ListView.View>
<GridView x:Name="DefaultGridView">
<GridViewColumn Width="Auto" Header="FC Port" DisplayMemberBinding="{Binding Path=FCPort}" />
<GridViewColumn Width="Auto" Header="WWPN" DisplayMemberBinding="{Binding Path=WWPN}"/>
<GridViewColumn Width="Auto" Header="FCID" DisplayMemberBinding="{Binding Path=FCID}" />
<GridViewColumn Width="Auto" Header="SwitchName" DisplayMemberBinding="{Binding Path=SwitchName}">
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
</TabItem>
這裏是應該載入它的代碼。
public class PortResult
{
public string SwitchName;
public string FCPort;
public string FCID;
public string WWPN;
public PortResult(string name, FCPort port)
{
SwitchName = name;
FCPort = String.Format("fc{0}/{1}", port.SlotNum, port.PortNum);
WWPN = port.WWPNList[0].WWPNValue;
FCID = port.WWPNList[0].FCIDValue;
}
}
ObservableCollection<PortResult> FCPortCollection = new ObservableCollection<PortResult>();
// results is an IEnumerable collection of FCPort result from a LINQ query that has been turned into a Dictionary
foreach (KeyValuePair<string, List<FCPort>> resultspair in results)
{
foreach (FCPort port in resultspair.Value)
{
// create a new PortResult and add it to the ObservableCollection
PortResult pr = new PortResult(resultspair.Key, port);
FCPortCollection.Add(pr);
}
}
知道[如何調試綁定](http://blogs.msdn.com/b/wpfsldesigner/archive/2010/06/30/debugging-data-bindings-in-a-wpf-or-silverlight-application的.aspx)? – 2012-02-21 18:27:48
我現在要做。 :)這是有幫助的。謝謝。 – 2012-02-21 19:21:40
不客氣,那些基礎知識很重要:) – 2012-02-21 19:23:35