2013-05-12 57 views
0

說我有編碼自定義Canvas這樣的:如何將自定義控件的類放入另一個自定義控件中?

public class MyCustomControl : Canvas 
    { 
     public MyCustomControl() 
     { 
      this.Background = System.Windows.Media.Brushes.LightBlue; 
     } 
    } 

,我需要把其他自定義編碼(自定義控件)Label裏面和使用整個項目作爲另一個項目ONE自定義控件。

我這樣做:

public class MyCustomControl : Canvas 
    { 
     public MyCustomControl() 
     { 
      this.Background = System.Windows.Media.Brushes.LightBlue; 
     } 
     //My custom label 
     public class MyLabel : Label 
     { 
      public MyLabel() 
      { 
       Content = "Hello!!"; 
       Width = 100; 
       Height = 25; 
       VerticalAlignment = System.Windows.VerticalAlignment.Center; 
       HorizontalAlignment = System.Windows.HorizontalAlignment.Center; 
      } 
     } 
    } 

但我沒有能看到Label其他項目中。請參閱圖片:
enter image description here
由於我在第一個項目中創建了自定義控件,因此我沒有可以依賴的可視引用(如XAML設計窗口或其他任何東西),基本上通過查看所有元素被正確編碼和可見。

首先,我不知道它是否是創建嵌套的自定義控件正確的方法。 第二,我不知道爲什麼標籤沒有顯示在那裏。這可能是因爲我必須將其添加到畫布上。但我不知道將代碼添加到它的父級,這是畫布。

回答

1

到標籤添加到畫布:

public MyCustomControl() 
{ 
    this.Background = System.Windows.Media.Brushes.LightBlue; 
    this.Children.Add(new MyLabel()); 
} 

但在這種情況下,你不需要自定義標籤:

public MyCustomControl() 
{ 
    this.Background = System.Windows.Media.Brushes.LightBlue; 
    this.Children.Add(new Label{ 
     Content = "Hello!!", 
     Width = 100, 
     Height = 25, 
     VerticalAlignment = System.Windows.VerticalAlignment.Center, 
     HorizontalAlignment = System.Windows.HorizontalAlignment.Center 
    }); 
} 

如果您希望能夠設計你的畫布,加UserControl到您的第一個項目。

<UserControl ...> 
    <Canvas Background="LightBlue"> 
     <Label Width="100" Height="25" VerticalAlignment="Center" HorizontalAlignment="Center"> 
      Hello!! 
     </Label> 
    </Canvas> 
</UserControl> 
+0

太感謝你了! 現在就去測試它)編輯:它的工作!非常感謝Lisp;) – Ali 2013-05-13 09:45:18