【发布时间】:2013-09-18 13:31:34
【问题描述】:
在 WPF 应用程序中,我有一个 ViewModel,它公开了一组字符串,我使用 WrapPanel 通过 ItemsControl 容器将这些字符串显示为按钮。但是,我无法将 ViewModel 中的 RelayCommand 绑定到按钮。
视图模型(IncidentAddressesViewModel):
public IEnumerable<string> Addresses { get; set; }
public RelayCommand<string> ZoomToAddressCommand { get {
if (this.zoomToAddressCommand == null) this.zoomToAddressComamnd = new RelayCommand<string>(this.ZoomToAddress);
return this.zoomToAddressCommand;
}}
private void ZoomToAddress(string address) { MessageBox.Show (address); }
XAML:
<TabItem x:Name="IncidentAddressesTab">
<ItemsControl ItemsSource="{Binding Addresses}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Command">
<cmd:EventToCommand
Command="{Binding ZoomToAddressCommand}"
CommandParameter="{Binding Text}"
PassEventArgsToCommand="True"
/>
</i:EventTrigger>
</i:Interaction.Triggers>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel Orientation="Vertical"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button Content="{Binding}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</TabItem>
连接DataContext的Xaml代码
IncidentAddressesTab.DataContext = new IncidentAddressesViewModel();
按钮与地址一起显示。当我在 ZoomToAddressCommand 处设置断点时,它会被命中一次,但是当我单击按钮时,ZoomToAddress 方法永远不会被调用。
更新以包含绑定详细信息: 我实际上绑定到 TabItem。我更新了 XAML 以包含附加标记,并在 XAML 代码隐藏中添加了绑定代码。我不知道这是相关信息,否则我会在开始时添加它..(:
【问题讨论】: