【发布时间】:2012-03-18 08:57:21
【问题描述】:
我目前正在开发一个使用 MVVM 的 WPF 应用程序。我有一个 ListBox,其样式设置为使其像 RadioButtonList 一样显示,如下所示:
<Style x:Key="RadioButtonList" TargetType="{x:Type ListBox}">
<Setter Property="BorderBrush" Value="{x:Null}" />
<Setter Property="BorderThickness" Value="0" />
<Setter Property="ItemContainerStyle">
<Setter.Value>
<Style TargetType="{x:Type ListBoxItem}" >
<Setter Property="Margin" Value="2" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListBoxItem}">
<Border Background="Transparent">
<RadioButton Focusable="False" IsHitTestVisible="False" IsChecked="{TemplateBinding IsSelected}" Content="{Binding Path=DisplayName}" Command="{Binding ElementName=ShippingWindow, Path=DataContext.ShipOtherMethodSelected}">
</RadioButton>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Setter.Value>
</Setter>
</Style>
<ListBox Name="lbShipOtherMethodOptions" Style="{StaticResource RadioButtonList}" ItemsSource="{Binding Path=ShipOtherMethodOptions}" Margin="13,74,366,282" />
我要做的是将命令绑定到 RadioButton,以便在进行选择时触发事件。我的视图模型中有以下代码,但我似乎无法启动它:
private ICommand shipOtherMethodSelected;
public ICommand ShipOtherMethodSelected
{
get
{
return shipOtherMethodSelected ??
(shipOtherMethodSelected = new RelayCommand(param => ShipOpenItems(), param => true));
}
}
private void ShipOpenItems()
{
MessageBox.Show("GOT HERE");
}
我对 WPF 和 MVVM 还很陌生,所以我可能遗漏了一些明显的东西。谁能指出我正确的方向?
编辑: 根据 jberger 的建议,我输入了一些我尝试过但不起作用的代码。在该部分设置断点没有被触发,消息框也没有出现。
编辑 2: 因此,在检查了发送方的 DataContext 之后,发现它指向的是我将 RadioButton 绑定到的对象,而不是我的视图模型。我更新了上面的代码(在我的窗口中添加了一个 x:Name 并更新了 Command 绑定),现在我让事件在最初绑定时触发,但是当我选择一个值时它不会触发。看来我们现在真的很接近了。
【问题讨论】:
-
你没有在你的 xaml 中绑定
ShipOtherMethodSelected -
对不起,我试过了,但在复制/粘贴我的代码之前我必须还原。我会解决的
-
如果您删除
Focusable="False" IsHitTestVisible="False"会发生什么?如果您挂钩Click事件,点击时会触发吗? -
删除 Focusable 和 IsHitTestVisible 并没有给我的结果带来任何变化。然而,挂钩 Click 事件确实触发了。我似乎无法让它绑定到我的 ICommand 似乎很奇怪。
-
在
Click事件处理程序中使用调试器浏览sender,并检查DataContext以确保它包含ShipOtherMethodSelected