Reputation: 3706
I can't figure this out. I thought I had the binding set properly but it's not firing. So I have a View:
<ListBox x:Name="EquipmentViewsListBox"
ItemsSource="{Binding EquipmentViews, UpdateSourceTrigger=PropertyChanged}"
SelectionMode="Extended"
BorderThickness="0"
Height="150"
Margin="5,5,10,10">
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding IsSelected, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=ListBox}, Path=DataContext.ViewSelected}"
CommandParameter="{Binding RelativeSource={RelativeSource Self}}"
Content="{Binding Name}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
I want to fire a command every time the checkbox in that ListBox
is selected. I created a command on my view model like so:
public class SdddViewModel : ViewModelBase
{
public SdddModel Model { get; set; }
public RelayCommand<ViewWrapper> ViewSelected { get; set; }
public SdddViewModel(SdddModel model)
{
Model = model;
ViewSelected = new RelayCommand<ViewWrapper>(OnViewSelected);
}
private void OnViewSelected(ViewWrapper obj)
{
var asd = obj;
}
}
So I understand that when I do a ListBox.ItemTemplate
the context for that item becomes the ListBoxItem
so in my case a class object ViewWrapper
. That works fine with the Name
binding for content as well with the IsSelected
property. It's the command that is not firing when item is checked. I set the relative ancestor to ListBox
and the Path=DataContext
but still nothing happens. Ideas?
Upvotes: 0
Views: 684
Reputation: 295
The problem is that the CommandParameter
doesn't match. You Declared it so the CommandParameter
is ViewWrapper
but you sent a parameter of type CheckBox
by using RelativeSource Self
. Change the CommandParameter
to simply {Binding}
which means it sends the DataContext
of the ListBoxItem
, which is ViewWrapper
.
You could have detected this binding error using Snoop.
Upvotes: 2