2011-05-11 91 views
11

正如你所知道的事件的情況下直接行爲,你不能綁定到一個命令:在風格的EventTrigger中觸發命令?

<DataGrid> 
    <i:Interaction.Triggers> 
     <i:EventTrigger EventName="PreviewMouseDoubleClick"> 
      <i:InvokeCommandAction Command="{Binding TradeEntryCommand"} /> 
     </i:EventTrigger> 
    </i:Interaction.Triggers> 
</DataGrid> 

這工作完全正常,但現在我已經從雙擊DataGrid中本身雙擊單元格重構這個。 (我不關心點擊了哪個小區)

我希望現在來定義單元格樣式像這樣這裏面behviour:

<Style x:Key="DefaultCellStyleBase" TargetType="{x:Type DataGridCell}"> 
    <Setter Property="Template"> 
     <Setter.Value> 
      <ControlTemplate TargetType="{x:Type DataGridCell}"> 
       <ControlTemplate.Triggers> 
        <EventTrigger RoutedEvent="PreviewMouseDoubleClick"> 
         ????????? 
        </EventTrigger> 
       </ControlTemplate.Triggers> 
      </ControlTemplate> 
     </Setter.Value> 
    </Setter> 
    <!-- ... --> 
</Style> 

但我怎麼會在行爲帶來從上面到火命令?

高度讚賞,

+0

這已經在SO上有很多關於定義風格行爲的SO。簡而言之:你不能,至少不能跳過很多複雜的代碼循環。我喜歡EventToCommand的行爲,但在這種情況下,我一直只需要在執行viewmodel命令的視圖上使用常規的EventSetter和方法處理程序。它感覺骯髒,它看起來很醜,涉及到所有的空值檢查,但是看過「解決方案」,它可能仍然更簡單,除非你發現自己在大型應用程序中遇到這麼多次。 – 2011-08-16 18:26:15

回答

7

既然你retemplating的DataGridCell,你可以在控制模板觸發器添加到根元素。喜歡的東西:

<ControlTemplate TargetType="{x:Type DataGridCell}"> 
    <Grid x:Name="root" Background="Transparent"> 
     <i:Interaction.Triggers> 
      <i:EventTrigger EventName="PreviewMouseDoubleClick"> 
       <i:InvokeCommandAction Command="{Binding TradeEntryCommand}" /> 
      </i:EventTrigger>        
     </i:Interaction.Triggers> 
    </Grid> 
</ControlTemplate> 
+0

代碼構建時,我無法獲得DataContext的權利,因爲它位於未指定的地方。我甚至試過這種沒有成功:<我:InvokeCommandAction命令= 「{結合TradeEntryCommand,的RelativeSource = {的RelativeSource FindAncestor,AncestorType =瀏覽次數:主窗口}}」/> – Houman 2011-05-11 14:26:58

+1

@Kave - 嘗試:命令=「{結合DataContext.TradeEntryCommand,的RelativeSource = {RelativeSource FindAncestor,AncestorType = Views:MainWindow}}「 – CodeNaked 2011-05-11 14:28:03

2

那一個版本,我在一個類似的情況(巴頓在DataGridRow使用一個按鈕命令,命令在DataGrid中應通過按鈕來調用,我需要的行的DataContext的在我的命令)。相反,您必須使用doubleClick-trigger的InvokeCommandAction命令,但它應該也可以運行,我想。

祝你好運!

<DataTemplate> 
      <TextBlock>        
      <Button x:Name="cmdButton"        
            Command="{Binding Path=DataContext.CommandNameInViewModel, 
             RelativeSource={RelativeSource AncestorType={x:Type TypeOfAncestorWithTheViewModel}}}" 
            CommandParameter="{Binding}" >  
            Do something 
     </Button> 

    </TextBlock> 
</DataTemplate>