I have searched around google about my problem and cant find any answer that can solve my problem.
I tried to binding a command from a button inside my datagrid in WPF. I used Prism to handle the MVVM.
Here is my code to bind the command:
<DataGrid AutoGenerateColumns="False"
...
SelectedItem="{Binding OrderDetail}"
ItemsSource="{Binding ListOrderDetail}">
<DataGrid.Columns>
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Content="Deliver Order"
Command="{Binding Path=DataContext.DeliverOrderCommand}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
and here is my viewmodel which contains the Command function:
public ICommand DeliverOrderCommand
{
get
{
if (deliverOrderCommand == null)
deliverOrderCommand = new DelegateCommand(DeliverOrderFunc);
return deliverOrderCommand;
}
set { deliverOrderCommand = value; }
}
When I tried to debug, it does not enter the ICommand.
So how can I bind my button inside the datagrid to my viewmodel?
Your problem is because DataColumns are not part of the visual tree and therefore do not inherit the DataContext of the DataGrid.
One way to potentially overcome this is to specify an ancestor with your binding:
Another (slightly hacky) way is to declare a helper class that creates an attached property for the DataGridColumn class and then populates that property when the datacontext of the grid changes (it does this by handling the event changed at the FrameworkElement level and checking if the dependency object responsible for the event is a DataGrid):
You can find more details about this approach here.