【问题标题】:How to bind commands to dynamically added buttons?如何将命令绑定到动态添加的按钮?
【发布时间】:2021-11-28 01:37:49
【问题描述】:

如何将委托命令绑定到动态添加的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 在哪里定义?在SomeCollection 或包含SomeCollection 的视图模型中的项目上?您如何以及在何处设置数据上下文?
  • @thatguy 它在包含 SomeCollection 的视图模型中!我在同一上下文中静态定义了其他按钮,并且工作正常。所以我想我的命令能够访问视图模型中的代码。但我不确定我是否必须为动态创建的按钮使用不同的命令。

标签: c# wpf xaml mvvm data-binding


【解决方案1】:

正如您在 ItemBoxButtonCommand 的 cmets 中所述:

它在包含 SomeCollection 的视图模型中!

当为SomeCollection中的每一项应用数据模板时,每一个DMX_ItemBox都会得到其DataContext设置的对应项,而不是包含SomeCollectionItemsControl的数据上下文。

为了绑定到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>

【讨论】:

    猜你喜欢
    • 2018-08-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-07
    • 1970-01-01
    • 1970-01-01
    • 2015-10-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多