-1

I have a WPF application using MVVM. I have a view with a View Model as its DataContext. Inside the View, I have a ListView binding to an observable collection. On each row of the ListView, I have a button that I want to bind to an ICommand in the DataContext. How do I set the RelativeSource to get to the DataContext ICommand?

xaml

<ListView ItemsSource="{Binding Services}"> <ListView.View> <GridView> <GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}" /> <GridViewColumn Header="Frequency" DisplayMemberBinding="{Binding Frequency}" /> <GridViewColumn Header="Type" DisplayMemberBinding="{Binding Type}" /> <GridViewColumn Header="Enable State" DisplayMemberBinding="{Binding EnableState}" /> <GridViewColumn Header="" > <GridViewColumn.CellTemplate> <DataTemplate> <Button Background="Transparent" BorderThickness="0" Command="{Binding RemoveTimerClick}" CommandParameter="{Binding}"> <Image Source="pack://application:,,,/Resources/Images/Delete.png" Width="20"/> </Button> </DataTemplate> </GridViewColumn.CellTemplate> </GridViewColumn> </GridView> </ListView.View> </ListView> 

This Command binding is looking for a the ICommand in the Services. I tried

Command="{Binding RemoveTimerClick, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}" 

But this didn't work because it is binding to the UserControl (which is the View), not the DataContext (which is the View model). How do I bind to the DataContext that also contains the Services collection?

2
  • How exactly this "does not work"? What error do you see (compile time error, runtime exception, binding error in the corresponding panel in the runtime, etc)? Commented Feb 29, 2024 at 15:21
  • This didn't work because it is binding to the UserControl (which is the View), not the DataContext (which is the View model). Commented Feb 29, 2024 at 16:00

1 Answer 1

0

Found the answer here. You have to add DataContext to the bound command:

Command="{Binding Path=DataContext.RemoveTimerClick, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}" CommandParameter="{Binding}" 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.