如何将命令绑定到动态添加的按钮?

How to bind commands to dynamically added buttons?

如何将委托命令绑定到动态添加的 UserControl 按钮?

我有我的 UserControl 按钮

<ItemsControl
    ItemsSource="{Binding SomeCollection}"
    HorizontalAlignment="Center">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <UniformGrid
                Columns="2" />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <DMX_ControlLibrary:DMX_ItemBox
                Width="250"
                Height="150"
                FontSize="12"
                Command="{Binding ItemBoxButtonCommand}"
                Content="{Binding Path=.}" />
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

在我的视图模型中,我有这个

private ICommand itemBoxButtonCommand;
public ICommand ItemBoxButtonCommand
{
    get { return (this.itemBoxButtonCommand) ?? (this.itemBoxButtonCommand = new DelegateCommand(ItemButton_Click)); }
}

private void ItemButton_Click()
{
    MessageBox.Show("");
}

Binding 似乎不像在静态添加的控件上那样工作。 我怎样才能让它发挥作用?

正如您在 ItemBoxButtonCommand 的评论中所述:

It's in the viewmodel that contains SomeCollection!

当数据模板应用于SomeCollection中的每个项目时,每个DMX_ItemBox将获得其DataContext设置相应的项目,而不是[=的数据上下文16=] 其中包含 SomeCollection.

为了绑定到 ItemBoxButtonCommand,您可以使用 RelativeSource 绑定到 ItemsControlDataContext(它是项目的父项) .

<ItemsControl.ItemTemplate>
   <DataTemplate>
      <DMX_ControlLibrary:DMX_ItemBox
         Width="250"
         Height="150"
         FontSize="12"
         Command="{Binding DataContext.ItemBoxButtonCommand, RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}}"
         Content="{Binding Path=.}" />
   </DataTemplate>
</ItemsControl.ItemTemplate>

或者,将 x:Name 分配给 ItemControl 并用 ElementName 引用它。

<ItemsControl
   x:Name="MyItemsControl"
   ItemsSource="{Binding SomeCollection}"
   HorizontalAlignment="Center">
   <ItemsControl.ItemsPanel>
      <ItemsPanelTemplate>
         <UniformGrid
            Columns="2" />
      </ItemsPanelTemplate>
   </ItemsControl.ItemsPanel>
   <ItemsControl.ItemTemplate>
      <DataTemplate>
         <DMX_ControlLibrary:DMX_ItemBox
            Width="250"
            Height="150"
            FontSize="12"
            Command="{Binding DataContext.ItemBoxButtonCommand, ElementName=MyItemsControl}"
            Content="{Binding Path=.}" />
      </DataTemplate>
   </ItemsControl.ItemTemplate>
</ItemsControl>