2013-08-26 107 views
0

我继承和创建我的自定义Canvas类是这样的:的WPF控件dose't从画布控制在画布上显示

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#代码添加子项到画布后,控件不会出现。

感谢您的任何建议。

回答

0

继承WPF控件至少可以说是problematic。 WPF控件的“看不见”。也就是说,控制本身并不知道它将如何呈现。当控件被放置在一个窗口中时,WPF会查找相应的ControlTemplate到这个特定的控件。

继承控件的问题是他们没有这样的模板。如果你想展示它,你必须自己写一个,而这并不总是很简单。你可以找到一个例子here,但我建议反对它。使用UserControlsinstead

+0

一个很好的回应和参考。谢谢! –