我有一個嵌套在ListBox的ItemTemplate內的數據網格。我試圖用這個來顯示一個像數據結構的樹。我的課程如下。列表框中嵌套的Datagrid
我的數據上下文中的對象包含一個名爲Sections
的List<Section>
,我的ListBox綁定到了這個。每個Section
包含一個名爲Items
的List<Item>
,eac ItemTemplate中的DataGrid綁定到此。
當我運行該應用程序時,從綁定行的XAML中得到一個空引用異常。有沒有更好的/可選的方式來做到這一點,或者我錯過了綁定的訣竅?
<Window.Resources>
<CollectionViewSource x:Key="SectionSource" /><!-- this is initialized and filled with an ObservableCollection<Section> Sections when the window loads-->
</Window.Resources>
<ListBox x:Name="lstIngredients" ItemsSource="{Binding Source={StaticResource SectionSource}}">
<ListBox.ItemTemplate>
<DataTemplate>
<DataTemplate.Resources>
<CollectionViewSource x:Key="itemsSource" Source="{Binding Items}"/>
</DataTemplate.Resources>
<DataGrid x:Name="dgItems" IsReadOnly="false" AutoGenerateColumns="False" SelectionMode="Single" SelectionUnit="FullRow" IsSynchronizedWithCurrentItem="True"
DataContext="{Binding}"
ItemsSource="{Binding Source={StaticResource Items}}"
EnableRowVirtualization="false"
VirtualizingStackPanel.VirtualizationMode="Standard"
<DataGrid.Columns>
<DataGridTemplateColumn Width="2*" Header="{lex:LocText ChickenPing.Shared:Strings:Measurement}">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock x:Name="quantity" Text="{Binding Measurement}" TextTrimming="CharacterEllipsis" TextAlignment="Left"/>
<!-- Null reference on this line caused by the binding. If I set this to any DependencyProperty on an Item object, I get a null reference-->
</DataTemplate>
同樣的錯誤很遺憾。對於TextBox文本綁定,我嘗試過'{Binding DataContext.MyProperty}'和'{Binding MyProperty}',但都沒有工作。 – Echilon 2012-04-07 18:40:11
讓我們從集合開始。在調試中加入「{Binding Path = PropertyThatIsCollection}」,並確保集合被調用。與TextBlock Path =相同,因爲綁定是相對的。您可以使用PresentationTrace High來獲取更多綁定錯誤。 – Paparazzi 2012-04-07 18:50:23