Wpf ListBox中的嵌套数据网格

Wpf ListBox中的嵌套数据网格,wpf,xaml,binding,datagrid,listbox,Wpf,Xaml,Binding,Datagrid,Listbox,我在列表框的ItemTemplate中嵌套了一个datagrid。我试图用这个来显示一个树状的数据结构。我的课程如下 我的数据上下文中的对象包含一个名为节的列表,我的列表框与此绑定。每个部分都包含一个名为项的列表,eac ItemTemplate中的DataGrid绑定到此列表 当我运行应用程序时,我在绑定行从XAML获得一个空引用异常。有没有更好的/替代的方法来实现这一点,或者我错过了绑定的一个技巧 <Window.Resources> <CollectionView

我在列表框的ItemTemplate中嵌套了一个datagrid。我试图用这个来显示一个树状的数据结构。我的课程如下

我的数据上下文中的对象包含一个名为
节的
列表
,我的列表框与此绑定。每个
部分
都包含一个名为
项的
列表
,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>

这需要一条路径

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

 ItemsSource="{Binding Path=PropertyThatIsCollection}"

并删除DataContext行

我最终找到了一个在TemplateColumns中设置的事件。将事件从


...

不幸的是,同样的错误。对于文本框文本绑定,我尝试了
{binding DataContext.MyProperty}
{binding MyProperty}
,但两者都不起作用。让我们从集合开始。在“{Binding Path=propertythatiscolection}”上的get中放置调试,并确保调用了该集合。与TextBlock Path=相同,因为绑定是相对的。您可以使用PresentationTrace High获取更多绑定错误。
<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} />