当按钮位于列表框项内时如何绑定命令

1 wpf binding mvvm

我在列表框内有按钮

 <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>
Run Code Online (Sandbox Code Playgroud)

在视图模型中

  public Command Remove{ get { return new Command(true, new System.Action(RemoveCmd)); } }
    public Command Change{ get { return new Command(true, new System.Action(ChangeCmd)); } }
Run Code Online (Sandbox Code Playgroud)

当我单击按钮时,方法不会被触发。我该如何解决这个问题?

小智 5

将您的命令绑定更改为:

<Button Command="{Binding DataContext.Remove, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBox}}}" />
<Button Command="{Binding DataContext.Change, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBox}}}" />
Run Code Online (Sandbox Code Playgroud)