2010-02-11 86 views
1

给定以下代码为什么“My Stupid Text”永远不会绑定到UserControls文本框?UserControl Property Binding not Working

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

下面的答案是好的,但我确实推动了这一来控制,而比UserControl和我的绑定现在好了。 – 2010-02-11 20:17:11

回答

2

不要在您的用户控制的构造下面(的InitializeComponent后)你的文本块应该知道它的datacontext:

this.DataContext = this; 
+0

这不起作用,用户控件本身没有'StupidText'属性。它还假设没有其他控件需要绑定到来自DataContext的典型数据源。元素到元素绑定是这里的解决方案。 – AnthonyWJones 2010-02-11 11:22:23

+0

你错了。 StupidText *是用户控件本身的属性,我的建议工作得很好。 – 2010-02-11 11:34:47

0

给你Stupid控制一个名字: -

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

然后你可以使用元素这样的结合: -

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