WPF - 在 ScrollViewer 中封装自定义 Canvas

WPF - Encapsulate custom Canvas in ScrollViewer

我需要一个自定义面板作为 Canvas,但实际上是一个内部带有 Canvas 的 ScrollViewer。用户应该能够像 canvas; 那样添加控件;我需要 ScrollViewer 包装器来处理缩放和平移行为。

于是,我开始写控件:

[ContentProperty("Children")]
public class MyContainer : ScrollViewer, IAddChild
{
    private Canvas _innerCanvas;

    [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
    public UIElementCollection Children
    {
        get { return _innerCanvas.Children; }
    }

    public MyContainer()
    {
        this._innerCanvas = new Canvas();
        this.Content = _innerCanvas;

        _innerCanvas.Height = this.ActualHeight;
        _innerCanvas.Width = this.ActualWidth;
    }

    void IAddChild.AddChild(object value)
    {
        _innerCanvas.Children.Add(value as UIElement);
    }

    void IAddChild.AddText(string text)
    {
        ;
    }
}

但它不起作用。如果我尝试在 XAML

中使用它
<Controls:MyContainer>
    <TextBlock Height="92" Canvas.Left="324" TextWrapping="Wrap" Text="TextBlock 1" Canvas.Top="267" Width="284"/>
    <TextBlock Height="92" Canvas.Left="462" TextWrapping="Wrap" Text="TextBlock 1" Canvas.Top="267" Width="284"/>
</Controls:MyContainer>

children 不可见。

怎么了?

您在 Ctor 中将 canvas 的大小设置为 ActualWidthActualHeight,但此时它们尚未初始化。 ActualWidthActualHeight 仅当控件显示在屏幕上时才有意义。尝试订阅 ScrollViewer 的 Loaded 事件,然后更改 Canvas 大小:

public MyContainer()
{
    this._innerCanvas = new Canvas();
    this.Content = _innerCanvas;

    this.Loaded += ScrollViewer_Loaded;
}

public void ScrollViewer_Loaded(object sender, EventArgs e)
{
    _innerCanvas.Height = this.ActualHeight;
    _innerCanvas.Width = this.ActualWidth;
}