2017-11-11 147 views
0

我想在DataGrid行上添加一個onclick事件,但它不適用於我的代碼。它只適用於TargetType="DataGridCell"。這是我的DataGrid;WPF DataGrid TargetType =「DataGridRow」not for Event =「MouseDoubleClick」

<DataGrid Name="CourtCasesGrid" Grid.Column="0" BeginningEdit="dataGrid_BeginningEdit" Grid.Row="0" SelectedItem="{Binding SelectedCourtCase}" CanUserReorderColumns="True" CanUserResizeColumns="True" CanUserResizeRows="False" CanUserSortColumns="True"> 
    <DataGrid.Resources> 
     <Style TargetType="DataGridRow"> 
      <EventSetter Event="MouseDoubleClick" Handler="CourtCasesGridRowDoubleClick"/> 
     </Style> 
    </DataGrid.Resources> 
</DataGrid> 

回答

0

我已經在這工作,併成功得到了上雙擊選定的刺激事件,同樣允許行的值要收集的行。我已經使用Code-Behind完成了這項工作,但如果這對您有用,也可以協助使用MVVM方法。

這裏的 'MainWindow.xaml' 後臺代碼:

using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows; 
using System.Windows.Controls; 
using System.Windows.Data; 
using System.Windows.Documents; 
using System.Windows.Input; 
using System.Windows.Media; 
using System.Windows.Media.Imaging; 
using System.Windows.Navigation; 
using System.Windows.Shapes; 

/// <summary> 
    /// Interaction logic for MainWindow.xaml 
    /// </summary> 
    public partial class MainWindow : Window 
    { 
     public DataGridRow SelectedRow { get; set; } 
     public ObservableCollection<CourtCase> CourtCases { get; set; } 
     public MainWindow() 
     { 
      InitializeComponent(); 

      CourtCases = new ObservableCollection<CourtCase>(); 
      CourtCases.Add(new CourtCase("1")); 
      CourtCases.Add(new CourtCase("2")); 
      CourtCases.Add(new CourtCase("3")); 
      CourtCases.Add(new CourtCase("4")); 

      SelectedRow = new DataGridRow(); 

      CourtCasesGrid.DataContext = CourtCases; 
     } 

     private void CourtCasesGridRowDoubleClick(object sender, MouseButtonEventArgs e) 
     { 
      DataGridRow row = sender as DataGridRow; 
     } 
    } 

這裏的 'MainWindow.xaml' 視圖:

<Grid> 
     <DataGrid ItemsSource="{Binding CourtCases,RelativeSource={RelativeSource FindAncestor, AncestorType=Window}}" Name="CourtCasesGrid" ColumnWidth="*" 
        SelectionUnit="FullRow"> 
      <DataGrid.Resources> 
       <Style TargetType="DataGridRow"> 
        <EventSetter Event="MouseDoubleClick" Handler="CourtCasesGridRowDoubleClick"/> 
       </Style> 
      </DataGrid.Resources> 
     </DataGrid> 
    </Grid> 

即使簡單的類我使用持有法庭數據,供您參考:

public class CourtCase 
{ 
    public string Name { get; set; } 
    public CourtCase() 
    { 
     Name = ""; 
    } 
    public CourtCase(string n) 
    { 
     Name = n; 
    } 
} 

希望能對您有所幫助!