Search code examples
c#wpfbindingdatatemplateitemsource

Datatemplate binding itemsource inside Datatemplate


I want to bind a ObservableCollection to a Itemscontrol inside a Datatemplate, that is inside another Datatemplate:

<ListView x:Name="list_befehlsfolge" Margin="5">
    <ListView.ItemTemplate>
        <DataTemplate DataType="{x:Type local:Befehlszeile}" >
            <Expander Margin="5" Header="{Binding Path=Bezeichnung,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}">
                <ItemsControl ItemsSource="{Binding Path=SubBefehlsliste}">
                    <DataTemplate DataType="{x:Type local:SubZeile_Text}">
                        <TextBox Text="{Binding Path=text,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"></TextBox>
                    </DataTemplate>
                </ItemsControl>
            </Expander>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

Binding the source to list_befehlsfolge.Itemsource with code behind is no problem, but how can I bind SubBefehlsliste?

When I create a new instance of SubBefehlsliste like

public class Befehlszeile : Position
{
    public string Bezeichnung { get; set; } = "Befehlsname";
 
    // crash at this line:  
    public ObservableCollection<Position> SubBefehlsliste { get; set; } = new ObservableCollection<Position>();
   
    public Befehlszeile()
    {
        //  SubBefehlsliste.Add(new SubZeile_Text());
    }
}

it crashes with an error

InvalidOperationException: The operation is invalid while using 'ItemsSource'. Instead, use ItemsControl.ItemsSource to access and modify items. (translated with google)

(Position is a "Mother"-class for all Datatypes like SubZeile_Text and other, to add all to a ObservableCollection)


Solution

  • Finally i found the problem, the Datatemplates must be inside "<ListView.Resources>" and "<ItemsControl.Resources>":

       <ListView x:Name="list_befehlsfolge" Margin="5">
            <ListView.Resources>
                <DataTemplate DataType="{x:Type local:Befehlszeile}" >
                    <Expander Margin="5" Header="{Binding Path=Bezeichnung,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}">
                        <ItemsControl ItemsSource="{Binding Path=SubBefehlsliste}">
    <ItemsControl.Resources>
                            <DataTemplate DataType="{x:Type local:SubZeile_Text}">
                                <TextBox Text="{Binding Path=text,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"></TextBox>
                            </DataTemplate>
    </ItemsControl.Resources>
                        </ItemsControl>
                    </Expander>
                </DataTemplate>
            </ListView.Resources>
        </ListView>