Command binding to a button inside a DataTemplate not working
Asked Answered
T

1

5

Example:

<ListBox Name="List" 
             ItemsSource="{Binding Items}" 
             SelectedIndex="{Binding SelectedIndex}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <DockPanel >
                    <Button DockPanel.Dock="Left" Content="Show" Command="{Binding ShowCommand}" CommandParameter="{Binding}"/>
                    <TextBlock Text="{Binding }"/>
                </DockPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

Clicking the button does nothing. I tried to bind the command to a button outside the DataTemplate and it works. I also tried to register the button in the DataTemplate to a Click_event and this did work.

Why is the command not working inside the DataTemplate?

Torpor answered 20/2, 2018 at 21:2 Comment(0)
T
10

Since the Command is defined in the ListBox's DataContext, Use either a RelativeSource Binding to help the Button locate the Command:

<ListBox.ItemTemplate>
    <DataTemplate>
        <DockPanel >
            <Button DockPanel.Dock="Left" Content="Show" Command="{Binding DataContext.ShowCommand,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type ListBox}}}" CommandParameter="{Binding}"/>
            <TextBlock Text="{Binding }"/>
        </DockPanel>
    </DataTemplate>
</ListBox.ItemTemplate>

Or use an ElementName binding:

<ListBox.ItemTemplate>
    <DataTemplate>
        <DockPanel >
            <Button DockPanel.Dock="Left" Content="Show" Command="{Binding DataContext.ShowCommand,ElementName=List}" CommandParameter="{Binding}"/>
            <TextBlock Text="{Binding }"/>
        </DockPanel>
    </DataTemplate>
</ListBox.ItemTemplate>
Twowheeler answered 20/2, 2018 at 21:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.