.net WPF:如何使画布自动调整大小?

.net WPF:如何使画布自动调整大小?,.net,wpf,resize,wpf-controls,scrollviewer,.net,Wpf,Resize,Wpf Controls,Scrollviewer,我希望我的Canvas自动调整其项目大小,以便ScrollViewer滚动条具有正确的范围。这可以在XAML中完成吗 <ScrollViewer HorizontalScrollBarVisibility="Auto" x:Name="_scrollViewer"> <Grid x:Name ="_canvasGrid" Background="Yellow"> <Canvas x:Name="_canvas" HorizontalAlign

我希望我的
Canvas
自动调整其项目大小,以便
ScrollViewer
滚动条具有正确的范围。这可以在XAML中完成吗

<ScrollViewer HorizontalScrollBarVisibility="Auto" x:Name="_scrollViewer">
    <Grid x:Name ="_canvasGrid" Background="Yellow">
        <Canvas x:Name="_canvas" HorizontalAlignment="Left" VerticalAlignment="Top" Background="Green"></Canvas>
        <Line IsHitTestVisible="False" .../>
    </Grid>
</ScrollViewer>

在上面的代码中,画布的大小始终为0,尽管它不会剪裁其子项。

否这是不可能的(请参阅下面MSDN中的片段)。但是,如果您想使用滚动条和自动调整大小,请考虑使用<强>网格> /强>,并使用保证金属性将您的项目定位在该网格上。Grid会告诉ScrollViewer他想要多大,你会得到滚动条。。画布将始终告诉ScrollViewer他不需要任何尺寸:)

网格让你们享受两个世界——只要你们把所有元素放在一个单元格中,你们就可以同时得到两个世界:任意定位和自动调整大小。一般来说,最好记住大多数面板控件(DockPanel、StackPanel等)都可以通过网格控件实现

发件人:


Canvas是唯一没有固有布局特征的面板元素。画布的默认高度和宽度属性为零,除非它是自动调整其子元素大小的元素的子元素。画布的子元素永远不会调整大小,它们只是定位在指定的坐标处。这为不需要或不需要固有大小限制或对齐的情况提供了灵活性。对于希望自动调整子内容大小和对齐的情况,通常最好使用网格元素


希望这有帮助

我知道你有一个可行的解决方案,但我想我会与大家分享

<Canvas x:Name="topCanvas">
    <Grid x:Name="topGrid" Width="{Binding ElementName=topCanvas, Path=ActualWidth}" Height="{Binding ElementName=topCanvas, Path=ActualHeight}">
        ...Content...
    </Grid>
</Canvas>

…内容。。。
上述技术将允许您在画布中嵌套网格并动态调整大小。进一步使用标注绑定可以将动态材质与静态材质混合,执行分层等。有太多的可能性值得一提,有些可能比其他更难。例如,我使用这种方法来模拟动画内容从一个网格位置移动到另一个网格位置-在动画的完成事件中进行实际放置。祝你好运。


<viewbox>
    <canvas>
        <uielements /> 
    </canvas>
</viewbox>

我认为您可以通过覆盖
MeasureOverride
ArrangeOverride
方法来调整
画布的大小

这项工作并不难

你可以看到这个帖子

我希望这对你有帮助


多谢各位

我只是在这里复制illef的答案,但在对PilotBob的回答中,您只需定义如下的画布对象

public class CanvasAutoSize : Canvas
{
    protected override System.Windows.Size MeasureOverride(System.Windows.Size constraint)
    {
        base.MeasureOverride(constraint);
        double width = base
            .InternalChildren
            .OfType<UIElement>()
            .Max(i => i.DesiredSize.Width + (double)i.GetValue(Canvas.LeftProperty));

        double height = base
            .InternalChildren
            .OfType<UIElement>()
            .Max(i => i.DesiredSize.Height + (double)i.GetValue(Canvas.TopProperty));

        return new Size(width, height);
    }
}
公共类画布AutoSize:画布
{
受保护的覆盖System.Windows.Size MeasureOverride(System.Windows.Size约束)
{
基础、测量超越(约束);
双倍宽度=底部
.儿童
第()类
.Max(i=>i.DesiredSize.Width+(双精度)i.GetValue(Canvas.LeftProperty));
双倍高度=底部
.儿童
第()类
.Max(i=>i.DesiredSize.Height+(双精度)i.GetValue(Canvas.TopProperty));
返回新尺寸(宽度、高度);
}
}
然后在XAML中使用CanvasAutoSize

            <local:CanvasAutoSize VerticalAlignment="Top" HorizontalAlignment="Left"></local:CanvasAutoSize>


与上面介绍的解决方案相比,我更喜欢使用网格,因为它通过附加属性工作,只需要在元素上设置较少的属性。

将高度/宽度绑定到画布中控件的实际大小适合我:

        <ScrollViewer VerticalScrollBarVisibility="Visible" HorizontalScrollBarVisibility="Visible">
            <Canvas Height="{Binding ElementName=myListBox, Path=ActualHeight}"
                    Width="{Binding ElementName=myListBox, Path=ActualWidth}">
                <ListBox x:Name="myListBox" />
            </Canvas>
        </ScrollViewer>

本质上,它需要完全重写画布。以前提出的覆盖MeasureOverride的解决方案失败,因为默认的Canvas.Left/.Top&c属性使排列无效,但也需要使MeasureOverride无效。(第一次获得正确的大小,但如果在初始布局之后移动图元,则大小不会改变)

网格解决方案或多或少是合理的,但为了获得x-y位移而绑定到边距可能会对其他代码造成严重破坏(尤其是在MVVM中)。我与网格视图解决方案斗争了一段时间,但视图/视图模型交互和滚动行为的复杂性最终驱使我这样做。这很简单,切中要害,很有效

重新执行排列覆盖和测量覆盖并没有那么复杂。而且你肯定会在其他地方写至少同样多的代码来处理网格/保证金的愚蠢行为。原来你在这里

这里有一个更完整的解决方案。非零保证金行为未经测试。如果您需要的不是左侧和顶部,那么这至少提供了一个起点

警告:必须使用AutoResizeCanvas.Left和AutoResizeCanvas.Top附加属性,而不是Canvas.Left和Canvas.Top。其余画布属性尚未实现

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Mu.Controls
{
    public class AutoResizeCanvas : Panel
    {



        public static double GetLeft(DependencyObject obj)
        {
            return (double)obj.GetValue(LeftProperty);
        }

        public static void SetLeft(DependencyObject obj, double value)
        {
            obj.SetValue(LeftProperty, value);
        }

        public static readonly DependencyProperty LeftProperty =
            DependencyProperty.RegisterAttached("Left", typeof(double),
            typeof(AutoResizeCanvas), 
            new FrameworkPropertyMetadata(0.0, OnLayoutParameterChanged));

        private static void OnLayoutParameterChanged(
                DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            // invalidate the measure of the enclosing AutoResizeCanvas.
            while (d != null)
            {
                AutoResizeCanvas canvas = d as AutoResizeCanvas;
                if (canvas != null)
                {
                    canvas.InvalidateMeasure();
                    return;
                }
                d = VisualTreeHelper.GetParent(d);
            }
        }




        public static double GetTop(DependencyObject obj)
        {
            return (double)obj.GetValue(TopProperty);
        }

        public static void SetTop(DependencyObject obj, double value)
        {
            obj.SetValue(TopProperty, value);
        }

        public static readonly DependencyProperty TopProperty =
            DependencyProperty.RegisterAttached("Top", 
                typeof(double), typeof(AutoResizeCanvas),
                new FrameworkPropertyMetadata(0.0, OnLayoutParameterChanged));





        protected override Size MeasureOverride(Size constraint)
        {
            Size availableSize = new Size(double.MaxValue, double.MaxValue);
            double requestedWidth = MinimumWidth;
            double requestedHeight = MinimumHeight;
            foreach (var child in base.InternalChildren)
            {
                FrameworkElement el = child as FrameworkElement;

                if (el != null)
                {
                    el.Measure(availableSize);
                    Rect bounds, margin;
                    GetRequestedBounds(el,out bounds, out margin);

                    requestedWidth = Math.Max(requestedWidth, margin.Right);
                    requestedHeight = Math.Max(requestedHeight, margin.Bottom);
                }
            }
            return new Size(requestedWidth, requestedHeight);
        }
        private void GetRequestedBounds(
                            FrameworkElement el, 
                            out Rect bounds, out Rect marginBounds
                            )
        {
            double left = 0, top = 0;
            Thickness margin = new Thickness();
            DependencyObject content = el;
            if (el is ContentPresenter)
            {
                content = VisualTreeHelper.GetChild(el, 0);
            }
            if (content != null)
            {
                left = AutoResizeCanvas.GetLeft(content);
                top = AutoResizeCanvas.GetTop(content);
                if (content is FrameworkElement)
                {
                    margin = ((FrameworkElement)content).Margin;
                }
            }
            if (double.IsNaN(left)) left = 0;
            if (double.IsNaN(top)) top = 0;
            Size size = el.DesiredSize;
            bounds = new Rect(left + margin.Left, top + margin.Top, size.Width, size.Height);
            marginBounds = new Rect(left, top, size.Width + margin.Left + margin.Right, size.Height + margin.Top + margin.Bottom);
        }


        protected override Size ArrangeOverride(Size arrangeSize)
        {
            Size availableSize = new Size(double.MaxValue, double.MaxValue);
            double requestedWidth = MinimumWidth;
            double requestedHeight = MinimumHeight;
            foreach (var child in base.InternalChildren)
            {
                FrameworkElement el = child as FrameworkElement;

                if (el != null)
                {
                    Rect bounds, marginBounds;
                    GetRequestedBounds(el, out bounds, out marginBounds);

                    requestedWidth = Math.Max(marginBounds.Right, requestedWidth);
                    requestedHeight = Math.Max(marginBounds.Bottom, requestedHeight);
                    el.Arrange(bounds);
                }
            }
            return new Size(requestedWidth, requestedHeight);
        }

        public double MinimumWidth
        {
            get { return (double)GetValue(MinimumWidthProperty); }
            set { SetValue(MinimumWidthProperty, value); }
        }

        public static readonly DependencyProperty MinimumWidthProperty =
            DependencyProperty.Register("MinimumWidth", typeof(double), typeof(AutoResizeCanvas), 
            new FrameworkPropertyMetadata(300.0,FrameworkPropertyMetadataOptions.AffectsMeasure));



        public double MinimumHeight
        {
            get { return (double)GetValue(MinimumHeightProperty); }
            set { SetValue(MinimumHeightProperty, value); }
        }

        public static readonly DependencyProperty MinimumHeightProperty =
            DependencyProperty.Register("MinimumHeight", typeof(double), typeof(AutoResizeCanvas), 
            new FrameworkPropertyMetadata(200.0,FrameworkPropertyMetadataOptions.AffectsMeasure));



    }


}
void主窗口\u已加载(对象发送器,路由目标)
{
autoSizeCanvas(canvas1);
}
void autoSizeCanvas(画布canv)
{
int height=canv.高度;
int WITH=canv.WITH;
foreach(canv.Children中的UIElement ctrl)
{
bool nullTop=ctrl.GetValue(Canvas.TopProperty)==null | | Double.IsNaN(Convert.ToDouble(ctrl.GetValue(Canvas.TopProperty)),
nullLeft=ctrl.GetValue(Canvas.LeftProperty)==null | | Double.IsNaN(Convert.ToDouble(ctrl.GetValue(Canvas.LeftProperty));
int curControlMaxY=(nullTop?0:Convert.ToInt32(ctrl.GetValue(Canvas.TopProperty)))+
Convert.ToInt32(ctrl.GetValue(Canvas.ActualWeightProperty)
),
curControlMaxX=(nullLeft?0:Convert.ToInt32(ctrl.GetValue(Canvas.LeftProperty)))+
Convert.ToInt32(ctrl.GetValue(Canvas.ActualWidthProperty)
);
高度=高度
void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
    autoSizeCanvas(canvas1);
}

void autoSizeCanvas(Canvas canv)
{
    int height = canv.Height;
    int width = canv.Width;
    foreach (UIElement ctrl in canv.Children)
    {
        bool nullTop = ctrl.GetValue(Canvas.TopProperty) == null || Double.IsNaN(Convert.ToDouble(ctrl.GetValue(Canvas.TopProperty))),
                nullLeft = ctrl.GetValue(Canvas.LeftProperty) == null || Double.IsNaN(Convert.ToDouble(ctrl.GetValue(Canvas.LeftProperty)));
        int curControlMaxY = (nullTop ? 0 : Convert.ToInt32(ctrl.GetValue(Canvas.TopProperty))) +
            Convert.ToInt32(ctrl.GetValue(Canvas.ActualHeightProperty)
            ),
            curControlMaxX = (nullLeft ? 0 : Convert.ToInt32(ctrl.GetValue(Canvas.LeftProperty))) +
            Convert.ToInt32(ctrl.GetValue(Canvas.ActualWidthProperty)
            );
        height = height < curControlMaxY ? curControlMaxY : height;
        width = width < curControlMaxX ? curControlMaxX : width;
    }
    canv.Height = height;
    canv.Width = width;
}
public class AutoResizedCanvas : Canvas
{
    protected override System.Windows.Size MeasureOverride(System.Windows.Size constraint)
    {
        base.MeasureOverride(constraint);
        double width = base
            .InternalChildren
            .OfType<UIElement>()
            .Where(i => i.GetValue(Canvas.LeftProperty) != null)
            .Max(i => i.DesiredSize.Width + (double)i.GetValue(Canvas.LeftProperty));

        if (Double.IsNaN(width))
        {
            width = 0;
        }

        double height = base
            .InternalChildren
            .OfType<UIElement>()
            .Where(i => i.GetValue(Canvas.TopProperty) != null)
            .Max(i => i.DesiredSize.Height + (double)i.GetValue(Canvas.TopProperty));

        if (Double.IsNaN(height))
        {
            height = 0;
        }

        return new Size(width, height);
    }
}
text2.SizeChanged += (s, e) => { DrawingCanvas.Height = e.NewSize.Height; 
                                 DrawingCanvas.Width = e.NewSize.Width; };