2013-08-26 81 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

一個很好的迴應和參考。謝謝! –