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