2012-08-24 41 views
0

我正在構建一個POS應用程序,我希望最終用戶能夠爲datagrid,I.E.提供切換選擇模式。他們可以點擊多行,每個單擊的項目將累積在SelectedItems屬性上 - 同時單擊已經選擇的行將取消選擇該行。我發現了另一個問題計算器此代碼:WPF DataGrid在CellTemplate中切換選擇模式和按鈕

<DataGrid.Resources> 
    <Style TargetType="{x:Type DataGridCell}"> 
     <EventSetter Event="PreviewMouseLeftButtonDown" Handler="DoCheckRow" /> 
    </Style> 
</DataGrid.Resources> 

public void DoCheckRow(object sender, MouseButtonEventArgs e) 
{ 
    DataGridCell cell = sender as DataGridCell; 
    if (cell != null && !cell.IsEditing) 
    { 
     DataGridRow row = VisualHelpers.TryFindParent<DataGridRow>(cell); 
     if (row != null) 
     { 
      row.IsSelected = !row.IsSelected; 
      e.Handled = true; 
      Debug.WriteLine(sender); 
     } 
    } 
} 

這實際上給了我但是我想盡可能的切換選擇模式,當我添加一個按鈕爲CellTemplate,按鈕命令不發射時點擊,因爲我在上面的代碼中設置了e.Handled = true;,它停止了事件泡泡。有沒有一種方法可以兼容?

回答

0

我能夠通過使用一些輔助功能,找到視覺父/子和一些命中測試來解決這個問題:

public void DoCheckRow(object sender, MouseButtonEventArgs e) 
{ 
    DataGridCell cell = sender as DataGridCell; 
    if (cell != null && !cell.IsEditing) 
    { 
     DataGridRow row = VisualHelpers.TryFindParent<DataGridRow>(cell); 
     if (row != null) 
     { 
      Button button = VisualHelpers.FindVisualChild<Button>(cell, "ViewButton"); 

      if (button != null) 
      { 
       HitTestResult result = VisualTreeHelper.HitTest(button, e.GetPosition(cell)); 

       if (result != null) 
       { 
        // execute button and do not select/deselect row 
        button.Command.Execute(row.DataContext); 
        e.Handled = true; 
        return; 
       } 
      } 

      row.IsSelected = !row.IsSelected; 
      e.Handled = true; 
     } 
    } 
} 

授予它不是最完美的解決方案,但它與MVVM模式的工作原理是我用。

1

也許你可以嘗試在你的按鈕上放置一個AttachedBehavior?通過這種方式,您可以從圖片中取出命令並處理AttachedBehavior中的click事件。

+0

好的建議。我嘗試了一個附加的行爲以及處理Click事件。它不會被調用。 –

+1

看看這個:http://stackoverflow.com/questions/2445106/wpf-two-commands-handlers-one-command –

+0

感謝您指出我在正確的方向!我能夠使用hittesting和一些幫助函數來解決它,以找到可視的孩子/父母。看到我的答案 –

0

你也可以用一個複選框來切換相應行上的選擇。

<DataGrid.RowHeaderTemplate> 
    <DataTemplate> 
     <CheckBox IsChecked="{Binding Path=IsSelected, Mode=TwoWay, 
          RelativeSource={RelativeSource FindAncestor, 
          AncestorType={x:Type DataGridRow}}}"/> 
    </DataTemplate> 
</DataGrid.RowHeaderTemplate>