0

DataGridCell 似乎不在控件的 VisualTree 中。

我有一个 DataGridTemplateColumn,它在网格内的堆栈面板中包含一个矩形和标签。

<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>

我希望PreviewMouseLeftButtonDown事件在可视树中向上迭代,直到找到父元素为空DataGridCell之后。Grid

private void swatch_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {          
            DataGridCell cell = null;

            while (cell == null)
            {
                cell = sender as DataGridCell;
                sender = ((FrameworkElement)sender).Parent;
            }

            MethodForCell(sender);
        }

阅读下面的链接,似乎在 DataGrid 的可视化树中 UIControls 被设置为DataGridCell. 那么如何从 Rectangle 中获取 DataGridCell 呢?

http://blogs.msdn.com/b/vinsibal/archive/2008/08/14/wpf-datagrid-dissecting-the-visual-layout.aspx

4

2 回答 2

2

在此更改您的事件处理程序:

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;
            }
        }
于 2012-07-19T20:34:30.337 回答
0

我发现这要好得多

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;
    }

你会这样称呼它:

var cell = GetVisualParent<DataGridCell>(e.Source);
于 2013-01-14T17:28:33.930 回答