如何將委托命令系結到動態添加的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與靜態添加的控制元件不同,這種方式似乎不起作用。我怎樣才能讓它作業?
uj5u.com熱心網友回復:
正如您在評論中所述ItemBoxButtonCommand:
它在包含 SomeCollection 的視圖模型中!
當資料模板應用于 中的每個專案時,每個專案SomeCollection都DMX_ItemBox將獲得其DataContext相應專案的集合,而不是ItemsControl包含 的的資料背景關系SomeCollection。
為了系結的ItemBoxButtonCommand,你可以使用RelativeSource系結到DataContext的ItemsControl(這是專案的母公司)。
<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>
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/313949.html
上一篇:如果MaxHeight小于MaxHeight,則使具有MaxHeight的元素占據Grid中的整個空間,否則固定到底部
