Replace a control within a user control through dependency property
I've made a simple project to illustrate my problem. I have a user control ('ButtonPod') that houses a button and a rectangle:
<UserControl x:Class="SilverlightDependencyProp.ButtonPod"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="400">
<Grid x:Name="LayoutRoot" Background="White">
<Rectangle Fill="Blue" />
<Button x:Name="ButtonOnPage" Margin="50" Content="Old button content" />
</Grid>
</UserControl>
I want to use this user control throughout my application, but I need to change the Button in the middle. I need control over all the properties of the Button, so I don't want to just expose DependencyProperties like 'ButtonText' or 'ButtonSize' - I would rather define the entire Button whenever I use the control. So I set up a dependency property ('CenterButton') like this:
public Button CenterButton
{
get { return (Button)GetValue(CenterButtonProperty); }
set { SetValue(CenterButtonProperty, value); }
}
public static readonly DependencyProperty CenterButtonProperty =
DependencyProperty.Register("CenterButton", typeof(Button),
typeof(ButtonPod), new PropertyMetadata(
CenterButtonChanged));
private static void CenterButtonChanged(DependencyObject d,
DependencyPropertyChangedEventArgs e)
{
var pod = d as ButtonPod;
pod.ButtonOnPage = e.NewValue as Button;
}
Then I try defining the 'CenterButton' on my MainPage.xaml, within my user control:
<Grid x:Name="LayoutRoot" Background="White">
<local:ButtonPod Width="200" Height="200">
<local:ButtonPod.CenterButton>
<Button Content="New button content" />
</local:ButtonPod.CenterButton>
</local:ButtonPod>
</Grid>
But when I load up the app, all I see is a button that says "Old button content" -- why isn't my button being replaced? Stepping through, I can see that the DependencyProperty gets hit and the 'ButtonOnPage' property开发者_运维百科 gets set, but the visual tree does not update. Any ideas?
Setting a named element does not replace it. You want to name the parent and add the child to that instead (replacing the existing children).
精彩评论