Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Command binding to a button inside a DataTemplate not working

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?

like image 646
Shachar Har-Shuv Avatar asked Mar 06 '23 20:03

Shachar Har-Shuv


1 Answers

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>
like image 94
SamTh3D3v Avatar answered Apr 06 '23 11:04

SamTh3D3v