【问题标题】:Getting DataGridCell from nested controls in the template column without iterating through the visual tree从模板列中的嵌套控件获取 DataGridCell 而无需遍历可视化树
【发布时间】:2012-07-19 13:49:14
【问题描述】:

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

【问题讨论】:

    标签: wpf datagrid wpfdatagrid visual-tree


    【解决方案1】:

    在这个上更改您的事件处理程序:

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

    【讨论】:

    • 谢谢!当我现在看到它时,它是如此简单,但它困扰了我好久。
    【解决方案2】:

    我发现这好多了

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-14
      • 2018-01-13
      • 1970-01-01
      • 1970-01-01
      • 2021-12-20
      相关资源
      最近更新 更多