ListBox项内的按钮时如何绑定命令

时间:2018-08-14 15:50:25

标签: wpf mvvm binding

我在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>

在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)); } }

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

1 个答案:

答案 0 :(得分:1)

将命令绑定更改为:

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