4

I'm trying to understand how XAML and code-behind talk to each other. I know that code-behind can access an element instantiated in XAML using the Name attribute eg:

Instantiate the button in XAML:

<SomeControlParent controlParent>
<Button Name=button1/>
<SomeControlParent controlParent>

Change properties of the button in code-behind:

button1.Content = "I created this button in XAML"

I was wondering if it was possible to do the opposite using XAML eg:

Instantiate the button in code-behind:

Button button1 = new Button();
controlParent.Child.Add(button1);

and then change the Content of the button using XAML.

Thanks! Soumaya

1
  • +1 Newbies sometimes ask the most interesting questions. It sounds like a basic one, but the answer is more complex than you'd initially think. But that's XAML for ya. There's a lot of new concepts to learn. Commented Dec 14, 2011 at 19:41

1 Answer 1

3

Having a code-behind lets you reference elements that have x:Name defined on them in XAML. Going the other direction, you can define properties on your UserControl and then reference them in XAML using a RelativeSource binding:

{Binding MyProperty, RelativeSource={RelativeSource Self}}

So in your example, you could have a property on your UserControl (although you'd probably want it to be a dependency property so you have change notification):

public Button Button1 { get; private set; }

And then insert it into your XAML using:

<ContentControl Content={Binding Button1, RelativeSource={RelativeSource Self}}>
    <ContentControl.Resources>
        <Style TargetType="Button">
            <Setter Property="Content" Value="Hey, I changed the name in XAML!"/>
        </Style>
    </ContentControl.Resources>
</ContentControl>
Sign up to request clarification or add additional context in comments.

6 Comments

I'm not sure if I'm doing this the right way. I added public Button Button1 { get; private set; } in the partial class that defines the window, and then <ContentControl Content="{Binding Button1, RelativeSource={RelativeSource Self}}"/> to the XAML but no luck...
Make Button1 into a dependency property as I mentioned. The easiest way to create one is type propdp then hit the tab key twice.
I did and VS tells me I'm not allowed to set the content twice. Maybe I should set the content control to some other property than Content on the first XAML line?
Oops. I forgot the enclosing <ContentControl.Resources> tags around the Style. I made the correction above.
Now it builds, but only if I use a CLR property, not a Dependency Property, and it looks completely empty, and it builds even if I use any text instead of Button1 after Binding ...
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.