2012-05-26 136 views
1

我有一個名爲myControl的UserControl,並且裏面有一個3列的Grid。將內容添加到UserControl

<Grid Name="main"> 
    <Grid Grid.Column="0"/><Grid Grid.Column="1"/><Grid Grid.Column="2"/> 
</Grid> 

客戶端可以以這種方式使用它並且沒問題。

<myControl /> 

我的問題是,客戶希望將元素添加到的「主」網格的第一列,如:

<myControl> 
    <TextBlock Text="abc"/> 
</myControl> 

在這種情況下,將TextBlock將取代創建的內容,在這裏它是「主」網格。

我該怎麼做才能支持附加元素?萬分感謝。

回答

2

您可以使用類似以下內容:

// This allows "UserContent" property to be set when no property is specified 
// Example: <UserControl1><TextBlock>Some Text</TextBlock></UserControl1> 
// TextBlock goes into "UserContent" 
[ContentProperty("UserContent")] 
public partial class UserControl1 : UserControl 
{ 
    // Stores default content 
    private Object defaultContent; 

    // Used to store content supplied by user 
    private Object _userContent; 
    public Object UserContent 
    { 
     get { return _userContent; } 
     set 
     { 
      _userContent = value; 
      UpdateUserContent(); 
     } 
    } 

    private void UpdateUserContent() 
    { 
     // If defaultContent is not set, backup the default content into it 
     // (will be set the very first time this method is called) 
     if (defaultContent == null) 
     { 
      defaultContent = Content; 
     } 

     // If there is something in UserContent, set it to Content 
     if (UserContent != null) 
     { 
      Content = UserContent; 
     } 
     else // Otherwise load default content back 
     { 
      Content = defaultContent; 
     } 
    } 

    public UserControl1() 
    { 
     InitializeComponent(); 
    } 
} 
+0

感謝您的幫助。它工作得很好。 – user1205398