How to bind command when button inside of ListBox Item

I have button inside of ListBox

 <ListBox HorizontalContentAlignment="Stretch" SelectedItem="{Binding SelectedUser}"  ItemsSource="{Binding Users}" >
                                <ListBox.ItemsPanel>
                                    <ItemsPanelTemplate>
                                        <WrapPanel />
                                    </ItemsPanelTemplate>
                                </ListBox.ItemsPanel>

                                <ItemsControl.ItemTemplate>
                                    <DataTemplate>

                                             <StackPanel>
                                                                <Button Command="{Binding Remove}" />
                                                                <Button Command="{Binding Change}"/>
                                                            </StackPanel>


                                    </DataTemplate>
                                </ItemsControl.ItemTemplate>
                            </ListBox>

In ViewModel

  public Command Remove{ get { return new Command(true, new System.Action(RemoveCmd)); } }
    public Command Change{ get { return new Command(true, new System.Action(ChangeCmd)); } }

Method is not fired when i click button. How can i fix that?

Upvotes: 1

Views: 1765

Answers (1)

Nebelkraehe
Nebelkraehe

Reputation: 234

Change your Command-Binding to:

<Button Command="{Binding DataContext.Remove, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBox}}}" />
<Button Command="{Binding DataContext.Change, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBox}}}" />

Upvotes: 5

Related Questions