2010-10-06 22 views

Trả lời

12

Bạn có thể muốn để thiết lập một số loại RelativeSource ràng buộc có thể giúp bạn có được "lưới phụ huynh/hàng" thông qua một {RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}, nhưng câu hỏi của bạn đã cho tôi suy nghĩ ...

Bạn có thể:

Sử dụng Reflection:

var gridCell = ....; 
var parentRow = gridCell 
     .GetType() 
     .GetProperty("RowOwner", 
       BindingFlags.NonPublic | BindingFlags.Instance) 
     .GetValue(null) as DataGridRow; 

Sử dụng VisualTreeHelper:

var gridCell = ...; 
var parent = VisualTreeHelper.GetParent(gridCell); 
while(parent != null && parent.GetType() != typeof(DataGridRow)) 
{ 
    parent = VisualTreeHelper.GetParent(parent); 
} 
0

Một cách để bạn có thể làm là bằng cách thông qua một hoặc cả hai trong những yếu tố cần thiết trong như một CommandParameter:

<MouseBinding 
    MouseAction="LeftDoubleClick" 
    Command="cmd:CustomCommands.Open" 
    CommandParameter="{Binding ElementName=MyDataGrid}}" /> 

Nếu bạn cần cả hai, bạn có thể thêm một bộ chuyển đổi đa giá trị kết hợp chúng thành một Tuple (hoặc để lại nó như là một đối tượng [])

sau đó, trong bạn code-behind bạn có thể truy cập nó bằng cách sử dụng e.Parameter

2

đây là những gì tôi nghĩ là một câu trả lời hoàn chỉnh ...

private void Copy(object sender, ExecutedRoutedEventArgs e) 
    { 
     DataGrid grid = GetParent<DataGrid>(e.OriginalSource as DependencyObject); 
     DataGridRow row = GetParent<DataGridRow>(e.OriginalSource as DependencyObject); 
    } 

    private T GetParent<T>(DependencyObject d) where T:class 
    { 
     while (d != null && !(d is T)) 
     { 
      d = VisualTreeHelper.GetParent(d); 
     } 
     return d as T; 
    } 
Các vấn đề liên quan