Reputation: 661
I have a UserControl named myControl and there is a 3 columns Grid within it.
<Grid Name="main">
<Grid Grid.Column="0"/><Grid Grid.Column="1"/><Grid Grid.Column="2"/>
</Grid>
The client can use it in this way and it is ok.
<myControl />
My problem is, the client want to add an Element into the first column of "main" Grid, like:
<myControl>
<TextBlock Text="abc"/>
</myControl>
In this case, the TextBlock will replace the originated Content, here it is the "main" Grid.
What should I do to support the additional element? Great thanks.
Upvotes: 1
Views: 460
Reputation: 30830
You can use something like following:
// 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();
}
}
Upvotes: 2