2012-02-28 30 views
7

Tôi đang cố gắng truy xuất thông tin hàng từ một biểu dữ liệu sau sự kiện nhấp đúp. Tôi có thiết lập sự kiện, nhưng bây giờ tôi chỉ cần thiết lập chức năng để lấy dữ liệu từ hàng.Nhận thông tin hàng sau một doubleclick

XAML:

<DataGrid 
     Width="Auto" 
     SelectionMode="Extended" 
     IsReadOnly="True" 
     Name="ListDataGrid" 
     AutoGenerateColumns="False" 
     ItemsSource="{Binding ListFieldObject.MoviesList}" 
     DataContext="{StaticResource MovieAppViewModel}" 
     cal:Message.Attach="[Event MouseDoubleClick] = [Action RowSelect()]"> 

     <DataGrid.Columns> 
      <DataGridTextColumn Width="200" IsReadOnly="True" Header="Title" Binding="{Binding Title}"/> 
      <DataGridTextColumn Width="100" IsReadOnly="True" Header="Rating" Binding="{Binding Rating}"/> 
      <DataGridTextColumn Width="100" IsReadOnly="True" Header="Stars" Binding="{Binding Stars}"/> 
      <DataGridTextColumn Width="93" IsReadOnly="True" Header="Release Year" Binding="{Binding ReleaseYear}"/> 
     </DataGrid.Columns> 
    </DataGrid> 

C# (MVVM ViewModel):

 public void RowSelect() 
    { 
     //now how to access the selected row after the double click event? 
    } 

Cảm ơn nhiều!

+0

Từ những gì tôi có thể nói đó là rất khó khăn nếu không muốn nói là không thể. Rất nhiều trang web thảo luận về điều này, ví dụ: http://www.scottlogic.co.uk/blog/colin/2008/12/wpf-datagrid-phát hiện được nhấp-ô-và-hàng/và http://stackoverflow.com/questions/5808616/how-to-bind-a-command-to- này double-click-on-a-row-in-datagrid – Phil

Trả lời

6

Với Caliburn nó là rất dễ dàng, chỉ cần vượt qua $ DataContext trên XAML của bạn:

cal:Message.Attach="[Event MouseDoubleClick] = [Action RowSelect($dataContext)]"> 

Và thay đổi phương pháp của bạn:

public void RowSelect(MoviesListItem movie) 
{ 
    //now how to access the selected row after the double click event? 
} 

// EDIT Xin lỗi, giải pháp trên sẽ chỉ làm việc nếu hành động là trên datatemplate chính nó ... một giải pháp khác sẽ được để có một ràng buộc SelectedItem và chỉ sử dụng nó trên phương pháp của bạn:

<DataGrid 
    SelectedItem="{Binding SelectedMovie,Mode=TwoWay}" 
    cal:Message.Attach="[Event MouseDoubleClick] = [Action RowSelect()]"> 

và trên mã của bạn:

public void RowSelect() 
{ 
    //SelectedMovie is the item where the user double-cliked 
} 
+0

Đây là cách tôi làm việc đó. Cảm ơn đã giúp đỡ! – Josh

+0

Giải pháp này là khả thi, nhưng từ kinh nghiệm, nó có nhược điểm của hành vi không thể đoán trước nếu người dùng đang nhanh chóng nhấp vào các khu vực của lưới dữ liệu của bạn. Ví dụ đáng chú ý nhất: người dùng thích nhấp nhanh vào mũi tên xuống hoặc theo dõi ngón tay cái trong thanh cuộn dọc nếu họ cuộn qua danh sách lớn. Nhiều người dùng không nhấp và kéo ngón tay cái để cuộn; thay vào đó, họ búa đi theo mũi tên hoặc theo dõi ngón tay cái. Giải pháp này sẽ luôn làm cho nhấp đúp để thực thi vì nó được xử lý bởi lưới dữ liệu chứ không phải hàng dữ liệu. – Adrian

+0

@Josh, giải pháp này cũng sẽ xử lý các nhấp chuột đôi vào tiêu đề cột, điều đó hầu như không cần thiết. Để ngăn chặn điều này, hãy xem xét giải pháp từ * David Kiff * dưới đây. – Sevenate

1

(hy vọng nó sẽ giúp) Tôi không chắc chắn về trường hợp của bạn, nhưng đây là những gì tôi làm trong winforms:

  int index = dataGridView2.CurrentRow.Index; //determine which item is selected 
      textBox8.Text = dataGridView2.Rows[index].Cells[0].Value.ToString(); //add login 
+0

bạn nhập được đánh giá cao nhưng tôi đang sử dụng mẫu MVVM và không thể có các cuộc gọi trong mã phía sau. Tôi sẽ chỉnh sửa bài gốc để phản ánh thực tế là C# nằm trong ViewModel. – Josh

1

Bạn có thể thực hiện việc này bằng cách sửa đổi mẫu điều khiển cho DataGridRows được DataGrid tiếp xúc. Ví dụ dưới đây sử dụng WPF và chủ đề Aero.

Điều duy nhất tôi đã thực hiện được xóa cal trước đó của bạn: Message.Attach gọi và di chuyển nó đến một "giữ chỗ" ContentControl mới bao quanh Border (x: Name = DGR_Border) trong mẫu điều khiển "mặc định". (Tôi đã từng ContentControl vì nó không có hình ảnh của riêng nó và nó cho thấy một sự kiện MouseDoubleClick.)

<DataGrid Width="Auto" 
      SelectionMode="Extended" 
      IsReadOnly="True" 
      Name="ListDataGrid" 
      AutoGenerateColumns="False" 
      ItemsSource="{Binding ListFieldObject.MoviesList}" 
      DataContext="{StaticResource MovieAppViewModel}"> 

    <DataGrid.Columns> 
     <DataGridTextColumn Width="200" IsReadOnly="True" Header="Title" Binding="{Binding Title}"/> 
     <DataGridTextColumn Width="100" IsReadOnly="True" Header="Rating" Binding="{Binding Rating}"/> 
     <DataGridTextColumn Width="100" IsReadOnly="True" Header="Stars" Binding="{Binding Stars}"/> 
     <DataGridTextColumn Width="93" IsReadOnly="True" Header="Release Year" Binding="{Binding ReleaseYear}"/> 
    </DataGrid.Columns> 
    <DataGrid.RowStyle> 
     <Setter Property="Background" Value="{DynamicResource {x:Static SystemColors.WindowBrushKey}}"/> 
     <Setter Property="SnapsToDevicePixels" Value="true"/> 
     <Setter Property="Validation.ErrorTemplate" Value="{x:Null}"/> 
     <Setter Property="ValidationErrorTemplate"> 
      <Setter.Value> 
       <ControlTemplate> 
        <TextBlock Foreground="Red" Margin="2,0,0,0" Text="!" VerticalAlignment="Center"/> 
       </ControlTemplate> 
      </Setter.Value> 
     </Setter> 
     <Setter Property="Template"> 
      <Setter.Value>          
       <ControlTemplate TargetType="{x:Type DataGridRow}"> 
        <ContentControl cal:Message.Attach="[Event MouseDoubleClick] = [Action RowSelect($datacontext)]"> 
         <Border x:Name="DGR_Border" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="True"> 
          <SelectiveScrollingGrid> 
           <SelectiveScrollingGrid.ColumnDefinitions> 
            <ColumnDefinition Width="Auto"/> 
            <ColumnDefinition Width="*"/> 
           </SelectiveScrollingGrid.ColumnDefinitions> 
           <SelectiveScrollingGrid.RowDefinitions> 
            <RowDefinition Height="*"/> 
            <RowDefinition Height="Auto"/> 
           </SelectiveScrollingGrid.RowDefinitions> 
           <DataGridCellsPresenter Grid.Column="1" ItemsPanel="{TemplateBinding ItemsPanel}" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/> 
           <DataGridDetailsPresenter Grid.Column="1" Grid.Row="1" SelectiveScrollingGrid.SelectiveScrollingOrientation="{Binding AreRowDetailsFrozen, ConverterParameter={x:Static SelectiveScrollingOrientation.Vertical}, Converter={x:Static DataGrid.RowDetailsScrollingConverter}, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}" Visibility="{TemplateBinding DetailsVisibility}"/> 
           <DataGridRowHeader Grid.RowSpan="2" SelectiveScrollingGrid.SelectiveScrollingOrientation="Vertical" Visibility="{Binding HeadersVisibility, ConverterParameter={x:Static DataGridHeadersVisibility.Row}, Converter={x:Static DataGrid.HeadersVisibilityConverter}, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}"/> 
          </SelectiveScrollingGrid> 
         </Border> 
        </ContentControl> 
       </ControlTemplate> 
      </Setter.Value> 
     </Setter> 
    </DataGrid.RowStyle> 
</DataGrid> 

Chỉ có điều khác bạn sẽ phải làm là thay đổi phương pháp RowSelect() của bạn để chấp nhận một tham số của bất cứ điều gì loại bạn đang sử dụng ở đây (tôi chỉ cho rằng đó là loại 'Phim').

public void RowSelect(Movie movie) 
{ 
    // do something with 'movie' 
} 
0

Ví dụ của tôi có cột có NAME "service_id". Nhưng bạn có thể sử dụng bù đắp cột int32. Thậm chí còn có ItemArray trong TYROWView TYPE để chạy và xuống. Xem System.Data không gian tên. Datagrid itemssource/context của bạn sẽ tác động đến "đối tượng" mà bạn nhìn thấy bên trong Datagrid. Nhưng nếu bạn kiểm tra gỡ lỗi các loại, sau đó bạn có thể Cast chúng và sử dụng chúng.

private void DataGridServiceRegistry_MouseDoubleClick(object sender, MouseButtonEventArgs e) 
{ 
    DataGrid DGSR = (DataGrid) sender; 
    var SR = (DataRowView) DGSR.CurrentItem; 
    var service_id = SR.Row["SERVICE_ID"]; 
} 
17

Hoặc bạn có thể làm điều này:

<DataGrid> 
    <DataGrid.RowStyle> 
     <Style TargetType="DataGridRow"> 
      <Setter Property="cal:Message.Attach" Value="[MouseDoubleClick] = [Action RowSelect($dataContext)]"/> 
     </Style> 
    </DataGrid.RowStyle> 
</DataGrid> 

Sau đó

public void RowSelect(MoviesListItem movie) 
{ 
    //now how to access the selected row after the double click event? 
} 
+2

Đây là giải pháp tốt hơn nhiều sau đó chấp nhận câu trả lời kể từ khi nó bắt chỉ nhấp đúp chuột vào hàng nhưng không phải trên tiêu đề. – Sevenate

+1

Đây là câu trả lời tôi đã tìm kiếm và phải được đánh dấu là câu trả lời. –

Các vấn đề liên quan