Question

I got a Listbox where each item is a Usercontrol MatchPanel. That UserControl has a button. I d like to remove an item when I click on the button of that item. I used the SelectedItem which is bind to my ViewModel and works well. But sometimes I m able to click on a button of one item without moving the SelectedItem value (the Listbox item dont get focused even if I click on the button of that item...). Hence I m looking for a way to receive in the command CloseSelectedMatchCommand a parameter which would tell me, for the button I have clicked, at which index of the Listbox it is. Thanks

Here is my View

<UserControl
    DataContext="{Binding ListTradingMatches, Source={StaticResource Locator}}" Height="503.175" Width="409">
    <ListBox ItemsSource="{Binding Path=ListMatches}" SelectedItem="{Binding Path=SelectedMatch}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel>
                    <local:MatchPanel />
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

Here is my MatchPanel UserControl

<UserControl x:Class="MatchPanel"
    <Label Content="Pts"/>
    <Button Command="{Binding RelativeSource={RelativeSource FindAncestor, 
                AncestorType={x:Type ListBox}}, 
                Path=DataContext.CloseSelectedMatchCommand}" CommandParameter="{Binding}">
    </Button>
</Grid>

Was it helpful?

Solution

You can set the DataContext of your UserControl to the item in the DataTemplate:

<DataTemplate>
    <StackPanel>
        <local:MatchPanel DataContext="{Binding}" />
    </StackPanel>
</DataTemplate>

Now the DataContext is set to the item from the collection, you can set the CommandParameter to the relevant property from that object...:

<Button Command="{Binding RelativeSource={RelativeSource FindAncestor, 
    AncestorType={x:Type ListBox}}, Path=DataContext.CloseSelectedMatchCommand}" 
    CommandParameter="{Binding Id}" />

..., or just the whole object:

<Button Command="{Binding RelativeSource={RelativeSource FindAncestor, 
    AncestorType={x:Type ListBox}}, Path=DataContext.CloseSelectedMatchCommand}" 
    CommandParameter="{Binding}" />
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top