Wpf 从模板列中的嵌套控件获取DataGridCell,而无需遍历可视化树
DataGridCell似乎不在控件的VisualTree中 我有一个DataGridTemplateColumn,它在网格内的堆栈面板中包含一个矩形和标签Wpf 从模板列中的嵌套控件获取DataGridCell,而无需遍历可视化树,wpf,datagrid,wpfdatagrid,visual-tree,Wpf,Datagrid,Wpfdatagrid,Visual Tree,DataGridCell似乎不在控件的VisualTree中 我有一个DataGridTemplateColumn,它在网格内的堆栈面板中包含一个矩形和标签 <t:DataGridTemplateColumn> <t:DataGridTemplateColumn.CellTemplate> <DataTemplate> <Grid FocusM
<t:DataGridTemplateColumn>
<t:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Grid FocusManager.FocusedElement="{Binding ElementName=swatch}">
<StackPanel Orientation="Horizontal">
<Rectangle Name="swatch" PreviewMouseLeftButtonDown="swatch_PreviewMouseLeftButtonDown" />
<Label/>
</StackPanel>
</Grid>
</DataTemplate>
</t:DataGridTemplateColumn.CellTemplate>
</t:DataGridTemplateColumn>
阅读下面的链接,似乎在DataGrid的可视树中uicontrol被设置为DataGridCell
的内容属性。那么如何从矩形中获取DataGridCell呢
在此事件上更改eventhandler:
private void swatch_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
DataGridCell cell = null;
while (cell == null)
{
cell = sender as DataGridCell;
if (((FrameworkElement)sender).Parent != null)
sender = ((FrameworkElement)sender).Parent;
else
sender = ((FrameworkElement)sender).TemplatedParent;
}
}
我觉得这样好多了
public static T GetVisualParent<T>(Visual child) where T : Visual
{
T parent = default(T);
Visual v = (Visual)VisualTreeHelper.GetParent(child);
if (v == null)
return null;
parent = v as T;
if (parent == null)
{
parent = GetVisualParent<T>(v);
}
return parent;
}
public static T GetVisualParent(可视子对象),其中T:Visual
{
T parent=默认值(T);
VisualV=(可视)VisualTreeHelper.GetParent(子级);
如果(v==null)
返回null;
父代=v为T;
如果(父项==null)
{
父对象=GetVisualParent(v);
}
返回父母;
}
你会这样称呼它:
var cell = GetVisualParent<DataGridCell>(e.Source);
var cell=GetVisualParent(e.Source);
谢谢!当我现在看到它的时候,它是如此的简单,但是它已经困扰了我很多年了。
var cell = GetVisualParent<DataGridCell>(e.Source);