获取父节点的高度

本文关键字:高度 父节点 获取 | 更新日期: 2023-09-27 18:10:44

我在运行时创建矩形和拇指作为一个孩子的画布。我想访问parent height,我的parent是sender事件中的一个canvas它被它的子事件调用。画布在运行时创建。在变量p中,我想访问父节点的高度

    private void Rectangle_Click(object sender, RoutedEventArgs e)
    {
        var canvas = new Canvas();
        canvas.Height = 100;
        canvas.Width = 100;
        canvas.Background = new SolidColorBrush(Colors.Violet);
        var thumb = new Thumb();
        thumb.Background = new SolidColorBrush(Colors.LimeGreen);
        var template = new ControlTemplate();
        thumb.Height = 20;
        thumb.Width = 20;
        thumb.DragDelta+=thumb_DragDelta;
        canvas.Children.Add(thumb);
        Canvas.SetTop(thumb, 90);
        Canvas.SetLeft(thumb, 90);

        canvas.ManipulationMode = ManipulationModes.All;
        canvas.ManipulationDelta += rec_ManipulationDelta;
        canvas.RenderTransform = new TranslateTransform(); // Create new TranslateTransform and assign to the rectangle
        board.Children.Add(canvas);
    }
    private void thumb_DragDelta(object sender, DragDeltaEventArgs e)
    {
        Thumb thumbSender = (Thumb)sender;
        var p= thumbSender.Parent;

        //double yadjust = recSender.Height + e.VerticalChange;
        //double xadjust = recSender.Width + e.HorizontalChange;
        //if ((xadjust >= 0) && (yadjust >= 0))
        {
            //recSender.Width = xadjust;
            //recSender.Height = yadjust;
            Canvas.SetLeft(thumbSender, Canvas.GetLeft(thumbSender) + e.HorizontalChange);
            Canvas.SetTop(thumbSender, Canvas.GetTop(thumbSender) + e.VerticalChange);
        }
    }

获取父节点的高度

既然你知道Thumb的父类是Canvas,你可以将它强制转换为Canvas类型&然后获取它的维度。

Canvas parentOfThumb = thumbSender.Parent as Canvas;
if (parentOfThumb != null) //if in case Parent is not canvas
    int p = parentOfThumb.ActualHeight;