2012-04-07 45 views
1

我有一個嵌套在ListBox的ItemTemplate內的數據網格。我試圖用這個來顯示一個像數據結構的樹。我的課程如下。列表框中嵌套的Datagrid

我的數據上下文中的對象包含一個名爲SectionsList<Section>,我的ListBox綁定到了這個。每個Section包含一個名爲ItemsList<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> 

回答

0

我終於跟蹤下來到這是在TemplateColumns的一個設置的事件。從

<TextBlock x:Name="quantity" Text="{Binding Measurement}" GotFocus="txt_GotFocus" />

切換事件

<Style x:Key="FocusableTextbox" TargetType="{x:Type TextBox}"> 
    <EventSetter Event="GotFocus" Handler="txt_GotFocus" /> 
</Style> 
... 
<TextBlock x:Name="quantity" Text="{Binding Measurement}" Style={StaticResource FocusableTextbox} /> 
0

這就需要將路徑

ItemsSource="{Binding Source={StaticResource Items}}" 

ItemsSource="{Binding Path=PropertyThatIsCollection}" 

,並刪除在DataContext線

+0

同樣的錯誤很遺憾。對於TextBox文本綁定,我嘗試過'{Binding DataContext.MyProperty}'和'{Binding MyProperty}',但都沒有工作。 – Echilon 2012-04-07 18:40:11

+0

讓我們從集合開始。在調試中加入「{Binding Path = PropertyThatIsCollection}」,並確保集合被調用。與TextBlock Path =相同,因爲綁定是相對的。您可以使用PresentationTrace High來獲取更多綁定錯誤。 – Paparazzi 2012-04-07 18:50:23