0

I have a ListBox :

<ListBox Margin="10" Padding="10" ItemsSource="{Binding Items}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <!-- Data template -->
            <Grid>
                <Grid.ColumnDefinitions>
                    <!--Image-->
                    <ColumnDefinition Width="auto" />
                    <!--Info-->
                    <ColumnDefinition Width="500" />
                    <!--Options-->
                    <ColumnDefinition Width="*" /
                </Grid.ColumnDefinitions>
                <Image Height="50" Width="50" />
                <StackPanel Grid.Column="1" HorizontalAlignment="Left">
                    <StackPanel Orientation="Horizontal">
                        <TextBlock Text="Name: " />
                        <TextBlock Text="{Binding Name}" />
                    </StackPanel>
                    <StackPanel Orientation="Horizontal">
                        <TextBlock Text="ID: " />
                        <TextBlock Text="{Binding ID}" />
                    </StackPanel>
                </StackPanel>
                <Button Grid.Column="2" Content="{Binding Status}" Command="{Binding CompleteCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:MainPageViewModel}}}" CommandParameter="{Binding}" HorizontalAlignment="Right" />
            </Grid>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

I need my CommandParameter be the ListItem of this ListBox.

3
  • ListItem? Do you mean the item with the ID and Status properties? Commented Nov 8, 2017 at 12:59
  • Yeap! Exactly ! Commented Nov 8, 2017 at 13:00
  • YES! Thanks everyone I did it and finished the project!!! Commented Nov 9, 2017 at 12:23

1 Answer 1

2

Set the AncestorType to ListBox and include DataContext in the path:

<Button ... Command="{Binding DataContext.CompleteCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBox}}}" CommandParameter="{Binding}" HorizontalAlignment="Right"></Button>

Then the Command binding should work provided that the CompleteCommand property belongs to the same class as the Items property

Sign up to request clarification or add additional context in comments.

5 Comments

Yes, I guess this is the class where the Items property is defined? It might be an idea to post the definition of the MainPageViewModel class.
You mean DataContext is the one which is used to Bind Items ?
DataContext returns the DataContext of the ListBox, which is the view model.
Thanks bro I got you.
No need. I made stupidly stupid mistake there. I have forgotten to put public to my CompleteCommand :(!!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.