开发者

UserControl Property Binding not Working

开发者 https://www.devze.com 2022-12-19 17:09 出处:网络
Given the following code why would \"My Stupid Text\" never be bound to the UserControls text box? MainPage.xaml

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"开发者_C百科
    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();
    }
}


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

this.DataContext = this;


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

精彩评论

暂无评论...
验证码 换一张
取 消