【发布时间】: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