Dawid Jabłoński
Dawid Jabłoński

Reputation: 17

How can I invoke button in datatemplate?

I have problem with worked button. I created pattern for display items with ObservableCollection but my button doesn't work.

Here I display items with dosent worked button

            <ItemsControl ItemsSource="{Binding Vehicles}">
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <Task:VehcileTask/>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>

Here is code displayed button with VehicleTask

            <Button Background="Red" Content="Delete"  Command="{Binding DeleteItem}">
            
        </Button>

This is command to invoke

        public ICommand DeleteItem { get; set; }

Upvotes: 0

Views: 48

Answers (1)

Peregrine
Peregrine

Reputation: 4566

Assuming that the DeleteItem command is a property of your main ViewModel, and not the individual data items, then you need to reference it via relative data binding.

Command="{Binding Path=DataContext.DeleteItem, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}}}"

You also need to include the item to be deleted as the CommandParameter of the Button

CommandParameter="{Binding}"

and to reference that parameter value within your command's corresponding method.

Upvotes: 1

Related Questions