给UserControl
元素 aName
然后绑定到它,如下例所示。如果您的文本不会更改,则应在调用InitialiseComponent
.
<UserControl x:Class="WpfApplication1.UserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300"
x:Name="root">
<Grid>
<TextBlock Text="{Binding SomeText,ElementName=root}"/>
</Grid>
</UserControl>
如果您SomeText
可能会更改,那么您需要将其声明为 aDependencyProperty
而不是普通的旧string
属性。这看起来像下面这样:
public string SomeText
{
get { return (string)GetValue(SomeTextProperty); }
set { SetValue(SomeTextProperty, value); }
}
// Using a DependencyProperty as the backing store for SomeText. This enables animation, styling, binding, etc...
public static readonly DependencyProperty SomeTextProperty =
DependencyProperty.Register("SomeText", typeof(string), typeof(UserControl1), new UIPropertyMetadata(""));
然后,您应该将绑定更改为如下所示,当您更改SomeString
.
<TextBlock Text="{Binding SomeText,ElementName=root,UpdateSourceTrigger=PropertyChanged}"/>