0

I have been trying to figure out this for two days now. I have a ListBox that is bound to an ObservableCollection. The ListBox is using a template to display a Button for each item in the collection. I want to fire a command and pass the selectedItem as a parameter when clicking the button.

The problem is when I click on the button the SelectedItem for the listBox is null, the listBox never gets the focus to change its selection. From what I found in SO the button click event is interrupting the ListBox SelectionChanged. Here is my XAML for the listBox, my view model uses Prism 6.3 DelegateCommand which publishes an event.

<ListBox Name="PatientsListBox" 
         ItemsSource="{Binding Patients}" 
         SelectedItem="{Binding SelectedPatient}"
         HorizontalContentAlignment="Stretch"
         >

        <ListBox.ItemTemplate>
            <DataTemplate>
                <Grid>
                    <Button Content="{Binding Path=Name}" 
                            Background="{Binding Path=Sex, Converter={StaticResource ColorConverter}}" 
                            Margin="0" Padding="0" 
                            Width="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBox}}, Path=ActualWidth, Mode=OneWay}" 
                            Command="{Binding ElementName=LayoutRoot, Path=DataContext.ShowPatientCommand}" 
                            CommandParameter="{Binding ElementName=PatientsListBox, Path=SelectedItem}">
                    </Button>
                </Grid>
            </DataTemplate>
        </ListBox.ItemTemplate>
        <ListBox.ItemContainerStyle>
            <Style TargetType="ListBoxItem">
                <Setter Property="HorizontalContentAlignment" Value="Stretch"></Setter>
            </Style>
        </ListBox.ItemContainerStyle>
    </ListBox>

Is it possible to do this without code behind, just using XAML?

I tried using ItemsControl but it doesn't have SelectedItem property. I also tried using interactivity with textBlock template but the command never fired.

Any ideas?

1 Answers1

0

I finally found an answer in MSDN forums Here is the full thread. I changed my CommandParameter binding to the following

CommandParameter="{Binding}"

This instructs WPF Command Manager to use the bound item of the DataTemplate. Miguel Fernández Corral

That's it. I hope that this will help someone in the future. cheers