Search code examples
wpfxamldatatemplateitemscontrolitemtemplate

How to add a button outside datatemplate in itemscontrol


I have created a WPF app.In that I have a Datatemplate as follows

 <DataTemplate x:Key="ItemTemplate">
    <StackPanel>
        <TextBlock Text="item"/>
        <TextBlock Text="{Binding Number}"/>
    </StackPanel>
 </DataTemplate>

I have an ItemsControl like this

 <ItemsControl ItemsSource="{Binding Items}"
                      Grid.Column="1"
                      Grid.Row="3"
                      ItemTemplate="{StaticResource ItemTemplateWithButton}" />

where I need a itemtemplate like this

    <DataTemplate x:Key="ItemTemplateWithButton">
        <StackPanel>
            <StackPanel>
                <TextBlock Text="item"/>
                <TextBlock Text="{Binding Number}"/>
            </StackPanel>
            <StackPanel>
                <Button>
                    <StackPanel>
                        <TextBlock Text="item"/>
                        <TextBlock Text="{Binding Number}"/>
                    </StackPanel>
                </Button>
            </StackPanel>
        </StackPanel>
    </DataTemplate>

Is there any possibility of reusing the datatemplate in the new itemscontrol?


Solution

  • You can use ContentControl too

    <DataTemplate x:Key="ItemTemplate">
        <StackPanel>
            <TextBlock Text="item"/>
            <TextBlock Text="{Binding Number}"/>
        </StackPanel>
    </DataTemplate>
    <DataTemplate x:Key="ItemTemplateWithButton">
        <StackPanel>
            <ContentControl ContentTemplate="{StaticResource ItemTemplate}" />
            <Button>
                <ContentControl ContentTemplate="{StaticResource ItemTemplate}" />
            </Button>
        </StackPanel>
    </DataTemplate>