鉴于以下代码,为什么“My Stupid Text”永远不会绑定到UserControls文本框?
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 :(得分:2)
在用户控件的构造函数中执行以下操作(在InitializeComponent之后),并且您的textblock应该知道它的datacontext:
this.DataContext = this;
答案 1 :(得分:0)
为您的Stupid
控件命名: -
<Local:Stupid x:Name="MyStupid" StupidText="My Stupid Text" />
然后你可以像这样使用元素绑定: -
<TextBlock Text="{Binding StupidText, ElementName=MyStupid}" />