James Hughes
James Hughes

Reputation: 6194

UserControl Property Binding not Working

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">
    <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();
    }
}

Upvotes: 1

Views: 594

Answers (2)

AnthonyWJones
AnthonyWJones

Reputation: 189457

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}" />

Upvotes: 0

Henrik S&#246;derlund
Henrik S&#246;derlund

Reputation: 4328

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

this.DataContext = this;

Upvotes: 2

Related Questions