tags:

views:

41

answers:

2

Given the following code why would "My Stupid Text" never be bound to the UserControls text box?

MainPage.xaml

<Grid x:Name="LayoutRoot">
    <Local:Stupid StupidText="My Stupid Text" />
</Grid>

Stupid.xaml

<UserControl x:Class="SilverlightApplication5.Stupid"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"&gt;
    <Grid x:Name="LayoutRoot" Background="White">
        <TextBlock Text="{Binding StupidText}" />
    </Grid>
</UserControl>

Stupid.xaml.cs

public partial class Stupid : UserControl
{
    public string StupidText
    {
        get { return (string)GetValue(StupidTextProperty); }
        set { SetValue(StupidTextProperty, value); }
    }

    // Using a DependencyProperty as the backing store for StupidText.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty StupidTextProperty =
        DependencyProperty.Register("StupidText", typeof(string), typeof(Stupid), new PropertyMetadata(string.Empty));

    public Stupid()
    {
        InitializeComponent();
    }
}
+1  A: 

Do the following in the constructor of your user control (after InitializeComponent) and your textblock should be aware of its datacontext:

this.DataContext = this;
Henrik Söderlund
This doesn't work, the user control itself does not have a `StupidText` property. It also assumes that there aren't other controls present that need to bind to typical data source from the DataContext. Element to element binding is the solution here.
AnthonyWJones
You're wrong. StupidText *is* a property of the user control itself, and my suggestion works just fine.
Henrik Söderlund
A: 

Give your Stupid control a name:-

<Local:Stupid x:Name="MyStupid" StupidText="My Stupid Text" />

Then you can use element binding like this:-

<TextBlock Text="{Binding StupidText, ElementName=MyStupid}" />
AnthonyWJones