Wpf 在样式内绑定命令
我目前正在开发一个使用MVVM的WPF应用程序。我有一个列表框,其样式设置使其显示为RadioButtonList,如下所示:Wpf 在样式内绑定命令,wpf,binding,mvvm,command,Wpf,Binding,Mvvm,Command,我目前正在开发一个使用MVVM的WPF应用程序。我有一个列表框,其样式设置使其显示为RadioButtonList,如下所示: <Style x:Key="RadioButtonList" TargetType="{x:Type ListBox}"> <Setter Property="BorderBrush" Value="{x:Null}" /> <Setter Property="BorderThickness" Value="0" />
<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" />
我是WPF和MVVM的新手,所以我可能遗漏了一些明显的东西。谁能给我指出正确的方向吗
编辑:
根据jberger的建议,我输入了一些我尝试过的代码,但没有成功。在该部分中设置断点没有出错,消息框也没有显示
编辑2:
因此,在检查发送方上的DataContext之后,发现它指向我将RadioButton绑定到的对象,而不是我的viewmodel。我更新了上面的代码(在我的窗口中添加了一个x:Name并更新了命令绑定),现在我得到了在初始绑定时触发的事件,但当我选择一个值时它不会触发。看起来我们现在真的很接近了。选择的
shipOtherMethods
在您的(主)ShippingVM
中,而不是您的ShipItemVM
,因此您需要设置
Command="{Binding ElementName=ShippingWindow, Path=DataContext.ShipOtherMethodSelected}"
其中ShippingWindow
是ListBoxItem
上方的元素的x:Name
另外,
Focusable=“False”ishitestvisible=“False”
拒绝单击。删除设置程序。所选的shipOtherMethods
位于您的(主)ShippingVM
中,而不是ShipItemVM
,因此您需要设置
Command="{Binding ElementName=ShippingWindow, Path=DataContext.ShipOtherMethodSelected}"
其中ShippingWindow
是ListBoxItem
上方的元素的x:Name
另外,
Focusable=“False”ishitestvisible=“False”
拒绝单击。删除设置程序。您没有在XAML中绑定ShipOtherMethodSelected
。对不起,我尝试了,但我必须在复制/粘贴代码之前还原。我将修复如果删除Focusable=“False”ishitestvisible=“False”
会发生什么情况?如果您挂接到Click
事件,它会在单击时触发吗?删除可聚焦和IshitteVisible不会对结果产生任何更改。然而,挂接到Click事件确实会触发。奇怪的是,我似乎无法让它绑定到我的ICommand。在中,单击事件处理程序,使用调试器浏览发送者,并检查数据上下文,以确保它包含ShipOtherMethodSelected
您没有在XAML中绑定ShipOtherMethodSelected
,对不起,我尝试过了,但我必须在复制/粘贴代码之前还原。我将修复如果删除Focusable=“False”ishitestvisible=“False”
会发生什么情况?如果您挂接到Click
事件,它会在单击时触发吗?删除可聚焦和IshitteVisible不会对结果产生任何更改。然而,挂接到Click事件确实会触发。奇怪的是,我似乎无法让它绑定到我的ICommand。在中,单击事件处理程序,使用调试器浏览发送方
,并检查数据上下文
,确保它包含ShipOtherMethodSelected