wpf - ListBox项内的按钮时如何绑定(bind)命令

标签 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>

在 View 模型中
  public Command Remove{ get { return new Command(true, new System.Action(RemoveCmd)); } }
    public Command Change{ get { return new Command(true, new System.Action(ChangeCmd)); } }

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

最佳答案

将您的命令绑定(bind)更改为:

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

关于wpf - ListBox项内的按钮时如何绑定(bind)命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51845335/

相关文章:

WPF 和超大图像

c# - WPF 将 List<custom> 绑定(bind)到 C# 代码中的组合框?

objective-c - 我绑定(bind)的对象的作用是什么?

c# - 防止 DataGrid 更新 MVVM 中的选定项

wpf - Silverlight WPF VisualStateManager 与 MultiDataTrigger

wpf - 新 WPF 功能区的深色背景变成渐变?

c# - 如何刷新 WPF 中的绑定(bind)?

validation - Android Databinding TextEdit Validation of two or more fields enable button

c# - 在前面使用图像和控件

wpf - 将 WPF 设计数据与 MVVM 模式一起使用