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"开发者_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}" />
精彩评论