Trong một trình xử lý sự kiện cho một lệnh cho một DataGrid, tôi nhận được DataGridCell trong ExecutedRoutedEventArgs. Tuy nhiên, tôi không thể tìm ra cách để có được DataGrid và DataGridRow liên quan của nó. Sự giúp đỡ của bạn được đánh giá rất cao.Làm thế nào để tìm chủ sở hữu của nó DataGrid và DataGridRow từ DataGridCell trong WPF?
14
A
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;
}