Take the 2-minute tour ×

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"
d:DesignHeight="300" d:DesignWidth="400">

    <Rectangle Fill="Blue" />
    <Button x:Name="ButtonOnPage" Margin="50" Content="Old button content" />


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(

    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:

    <local:ButtonPod Width="200" Height="200">
            <Button Content="New button content" />   

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?

share|improve this question
add comment

1 Answer

up vote 1 down vote accepted

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).

share|improve this answer
Right, but doesn't replacing <Button x:Name="ButtonOnPage" Margin="50" Content="Old button content" /> with the new button (via pod.ButtonOnPage = e.NewValue as Button;) affect the visual tree? The property is just the way to set the new button.. or so I thought. –  Nick B Jun 29 '11 at 18:24
Thanks -- the problem is that x:Name just makes a reference to what's on the page, which you can't change.. basically like a get without a set. Thanks for the help. –  Nick B Jun 29 '11 at 18:32
@Nick Bradley: If you have a look at the generated designer code, you will see that it has a member per named element. These are connected to the Xaml, but are still also just properties. By setting a named property you are just replacing a class member, but are not connecting it to the visual tree. I guess those properties should all be marked 'readonly' –  TrueBlueAussie Jun 30 '11 at 7:25
Yep, right on - thanks for your explanation! +1 –  Nick B Jun 30 '11 at 12:33
add comment

Your Answer


