Datagrid binding command with WPF prism

I searched around google about my problem and cannot find an answer that can solve my problem. I tried to associate a command with a button inside my datagrid in WPF. I used Prism to handle MVVM. Here is my code for binding 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 view model that 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 ICommand. So, how can I link my button inside a datagrid with my view model?

+4
source share
1 answer

Your problem is that DataColumns are not part of the visual tree and therefore do not inherit the DataContext DataGrid.

One way to potentially overcome this is to specify an ancestor with your binding:

 <DataGridTemplateColumn.CellTemplate> <DataTemplate> <Button Content="Deliver Order" Command="{Binding Path=DataContext.DeliverPesananCommand ,RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}" /> </DataTemplate> </DataGridTemplateColumn.CellTemplate> 

Another (slightly hacked) way is to declare a helper class that creates an attached property for the DataGridColumn class and then populates this property when the grid data type changes (it does this by handling the event changed at the FrameworkElement level and checking if the dependency object is responsible for the DataGrid event):

 public class DataGridContextHelper { static DataGridContextHelper() { DependencyProperty dp = FrameworkElement.DataContextProperty.AddOwner(typeof(DataGridColumn)); FrameworkElement.DataContextProperty.OverrideMetadata( typeof(DataGrid) ,new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.Inherits, OnDataContextChanged) ); } public static void OnDataContextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var grid = d as DataGrid; if (grid == null) return; foreach (var col in grid.Columns) { col.SetValue(FrameworkElement.DataContextProperty, e.NewValue); } } } 

You can find more about this approach here .

+3
source

Source: https://habr.com/ru/post/1445441/


All Articles