2015-04-08 152 views
0

我在我的視圖中有一個DataGrid,DataGrid的單元格帶有按鈕,它們分配了命令。現在我希望將當前行對象(位於DataGrid.CurrentItem中)傳遞給命令執行邏輯。如何在命令執行前轉換命令參數?

我最初的想法是使用CommandParameter與值轉換器,其中轉換器將DataGrid作爲參數,並從DataGrid中提取所需信息到我自己的類 - 以這種方式,我會避免從我的視圖模型引用DataGrid。

問題是,當顯示網格時執行CommandParameter綁定/值轉換,這意味着沒有選定的項目。

我可以以某種方式避免將DataGrid引用引入我的命令執行邏輯,如deffer CommandParameter解析,直到命令執行或類似的東西?

更新:我需要CurrentItem和CurrentColumn,我已經意識到,CurrentItem可能可以通過SelectedItem的綁定來訪問,所以避免接受提議使用SelectedItem屬性的答案。

+1

你有沒有試過,我認爲當你觸發命令綁定執行。 – Bolu

+0

@Bolu - 是的,我試過了,綁定在渲染數據網格時執行,而不是在單擊按鈕時執行。 – Giedrius

+0

你想發送什麼命令參數,我想大部分可以通過按鈕的命令綁定完成 – Muds

回答

3

所以我最初的想法已經足夠接近了。

當我將CommandParameter綁定到DataGrid時,問題是,當綁定被解析時,DataGrid不知道什麼是CurrentColumn或CurrentCell或CurrentItem,所以它解析爲空值。

因此,我改變綁定綁定到DataGridCell,而不是問題解決了 - Cell有能力在綁定解析時告訴它的屬於它的列和項,所以當命令被觸發時,它已經擁有了所有正確的數據。

風格一直在尋找這樣的事情:

<Button Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}},  
          Path=DataContext[RowActionFeature].RowActionCommand}"                          
     CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type DataGridCell}}, 
            Converter={StaticResource DataGridCellToRowActionParametersConverter}}"> 
... 
</Button> 

器和轉換器是這樣的:

public class DataGridCellToRowActionParametersConverter : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     var dataGridCell = value as DataGridCell; 

     if (dataGridCell == null) 
     { 
      return null; 
     } 

     var dataRowView = dataGridCell.DataContext as DataRowView; 
     var columnIndex = dataGridCell.Column.DisplayIndex; 

     return new RowActionParameters 
       { 
        Item = dataGridCell.DataContext, 
        ColumnPropertyName = dataGridCell.Column.SafeAccess(x => x.SortMemberPath), 
        DataRowView = dataRowView,      
        ColumnIndex = columnIndex 
       }; 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     throw new NotImplementedException(); 
    } 
} 
2
  • 你的命令參數應該只是CommandParameter="{Binding}" 這樣的參數會裏被點擊的按鈕是一個實例模型中的行DataContext
  • 在您的commadns Execute 方法中將您的參數轉換爲您的模型。
  • 說,例如,你想阻止命令執行 如果的SelectedItem爲null,或者該項目已被選中,然後 所有你需要的是在任何你想要的基於 從CanExecute方法返回一個布爾。
+0

解決了CurrentItem問題,但沒有回答如何獲得CurrentColumn。 – Giedrius

+0

@Giedrius你有同一行中的多個按鈕和相同的命令? –

+0

是的,我使用DataGridCell風格,所以風格是按鈕,它的命令描述 - 所以是的,我需要以某種方式識別那是什麼按鈕。 – Giedrius