0

我从画布控件继承,并像这样创建自定义画布类:

public class MyCanvas:Canvas
{
    //this list will contains all shape
    VisualCollection graphicsList;
    List<GraphicsBase> cloneGraphicsList;
    int c = 0;
    double deltaX = 0;
    double deltaY = 0;
    public MyCanvas()
        :base()
    {
        graphicsList = new VisualCollection(this);
        cloneGraphicsList = new List<GraphicsBase>();
    }

   public VisualCollection GraphicsList
    {
        get
        {
            return graphicsList;
        }
        set
        {
            graphicsList = value;
        }
    }

    protected override int VisualChildrenCount
    {
        get
        {
            return graphicsList.Count;
        }
    }

    protected override Visual GetVisualChild(int index)
    {
        if (index < 0 || index >= graphicsList.Count)
        {
            throw new ArgumentOutOfRangeException("index");
        }
        return graphicsList[index];
    }
    public GraphicsBase this[int index]
    {
        get
        {
            if (index >= 0 && index < GraphicsList.Count)
            {
                return (GraphicsBase)GraphicsList[index];
            }
            return null;
        }
    }

    public int Count
    {
        get
        {
            return GraphicsList.Count;
        }
    }
 }

并在 XAML 中使用此代码:

<Window x:Class="MyNameSpace.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:CustomCanvas="clr-namespace:MyNameSpace"
xmlns:WPFRuler="clr-namespace:Orbifold.WPFRuler;assembly=Orbifold.WPFRuler"
Title="PrintVarsDesigner" Height="709" Width="964"
Background="LightGray" Grid.IsSharedSizeScope="False" OverridesDefaultStyle="False" 
WindowState="Maximized" WindowStartupLocation="CenterScreen">
  <CustomCanvas:MyCanvas x:Name="myCanvas" Background="White" VerticalAlignment="Top" 
      Width="895" Height="1162">
  </CustomCanvas:MyCanvas>
</Window>

通过将子项添加到画布从可视屏幕或 C# 代码添加控件后,控件不会出现。

感谢您的任何建议。

4

1 回答 1

0

至少可以说继承 WPF 控件是有问题的。WPF 控件是“无视的”。也就是说,控件本身并不知道它会如何呈现。当控件被放置在一个窗口中时,WPF 会寻找与ControlTemplate这个特定控件对应的。

继承控件的问题是它们没有这样的模板。如果你想展示它,你必须自己写一个,这并不总是那么简单。你可以在这里找到一个例子,但我建议不要这样做。改用UserControls_

于 2013-08-26T09:00:56.147 回答