I’m currently working on a WPF application that uses MVVM. I’ve got a ListBox with a style set up to make it display like a RadioButtonList as follows:
<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" />
What I’m trying to do is bind a command to the RadioButton, so that I can fire off an event when a selection is made. I’ve got the following code in my viewmodel, but I can’t seem to get it to fire:
private ICommand shipOtherMethodSelected;
public ICommand ShipOtherMethodSelected
{
get
{
return shipOtherMethodSelected ??
(shipOtherMethodSelected = new RelayCommand(param => ShipOpenItems(), param => true));
}
}
private void ShipOpenItems()
{
MessageBox.Show("GOT HERE");
}
I’m pretty new to WPF and MVVM, so I’m probably missing something obvious. Can anyone point me in the right direction?
EDIT:
Per jberger’s suggestion, I put in some code that I attempted that didn’t work. Setting breakpoints in that section didn’t get tripped, nor did the message box show up.
EDIT 2:
So after inspecting the DataContext on the sender, it turns out it was pointing to the object that I’m binding the RadioButton to, and not my viewmodel. I updated the code above (adding in an x:Name to my window and updating the Command binding), and now I’m getting the event to fire when its initially bound, but it doesn’t fire when I select a value. Seems like we’re getting really close now.
The
ShipOtherMethodSelectedis in your (main)ShippingVMNOT yourShipItemVM, so you need to setwhere
ShippingWindowis thex:Nameof an element “above” theListBoxItemAlso, the
Focusable="False" IsHitTestVisible="False"is denying the click. Remove the setters.