2008-10-16 75 views
0

我想創建一個具有兩個內容區域的Silverlight 2控件。標題和主要內容。因此控制將是:如何創建具有兩個內容區域的Silverlight控件

<StackPanel> 
<TextBlock Text=" CONTENT1 "/> 
<Content with CONTENT2 "/> 
</StackPanel> 

當我使用控制我應該只可以使用:

<MyControl Text="somecontent">main content </MyControl> 

如何創建這樣的控制?

回答

7

您可以使用ContentProperty屬性輕鬆完成此操作。

然後,你可以定義你的代碼背後:

[ContentProperty("Child")] 
public partial class MyControl: UserControl 
{ 
    public static readonly DependencyProperty ChildProperty = DependencyProperty.Register("Child", typeof(UIElement), typeof(MyControl), null); 

    public UIElement Child 
    { 
     get { return (UIElement)this.GetValue(ChildProperty); } 
     set 
     { 
      this.SetValue(ChildProperty, value); 
      this.content.Content = value; 
     } 
    } 

什麼,將要做的是你的標籤(<MyControl Text="somecontent">main content </MyControl>)內的任何默認的內容 - 將被設置爲你的類子屬性。然後,一旦設置好,您可以將其分配給您喜歡的任何控件。

編輯:

你可以有很多內容你喜歡,但你只能有1自動內容(通過ContentProperty屬性指定)。 如果你希望兩個你可以這樣做:

<MyControl> 
    <MyControl.Content1>Hello World</MyControl.Content1> 
    <MyControl.Content2>Goodbye World</MyControl.Content2> 
</MyControl> 

所有你需要做的就是確保你在你的代碼匹配的依賴屬性。然後,在設置屬性時,只需將其分配給XAML中的父內容控件即可。

+0

完美,我可以有兩個內容? – Peter 2008-10-16 09:59:59

相關問題