WPF - 在ScrollViewer中封装自定义Canvas

时间:2015-05-25 08:41:13

标签: c# wpf xaml canvas scrollviewer

我需要一个自定义面板作为Canvas,但实际上是一个内置Canvas的ScrollViewer。用户应该能够像在画布中一样添加控件;我需要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>

孩子们不可见。

有什么问题?

1 个答案:

答案 0 :(得分:2)

您可以在Ctor中将画布的大小设置为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;
}