2010-02-11 82 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}" />