2012-11-12 143 views
4

我搜索了谷歌有關我的問題,並找不到任何答案可以解決我的問題。 我試圖綁定WPF中我的datagrid中的按鈕的命令。我使用Prism來處理MVVM。 這裏是我的代碼綁定命令:Datagrid與棱鏡綁定命令WPF

<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> 

,這裏是我的視圖模型包含命令功能:

public ICommand DeliverOrderCommand 
    { 
     get 
     { 
      if (deliverOrderCommand == null) 
       deliverOrderCommand = new DelegateCommand(DeliverOrderFunc); 
      return deliverOrderCommand; 
     } 
     set { deliverOrderCommand = value; } 
    } 

當我試圖調試,它不進入ICommand的。 那麼如何將datagrid中的按鈕綁定到我的viewmodel?

回答

3

您的問題是因爲DataColumns不是可視樹的一部分,因此不會繼承DataGrid的DataContext。

一個潛在克服這種方式與你綁定指定一個祖先:

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

另一個(略哈克)的方式是聲明DataGridColumn類的,然後填充創建一個附加屬性的輔助類該屬性時的網格變化(由它處理事件在FrameworkElement的層次變化,檢查是否對事件負責的依賴對象是一個DataGrid做到這一點)在DataContext:

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); 
     } 
    } 
} 

你可以找到鐵道部有關此方法的詳細信息here

+1

謝謝@slugster我的問題使用第一種方法解決。 :d – ganiamri