如何:创建简单绑定
此示例演示如何创建简单的 Binding。
示例
在此示例中,假设您具有一个字符串属性名为 PersonName 的 Person 对象。 Person 对象是在名为 SDKSample 的命名空间中定义的。
下面的示例用值为 Joe 的 PersonName 属性来实例化 Person 对象。 这是在 Resources 部分中完成的,系统会为该对象分配一个 x:Key。
<Window
xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
xmlns:src="clr-namespace:SDKSample"
SizeToContent="WidthAndHeight"
Title="Simple Data Binding Sample">
<Window.Resources>
<src:Person x:Key="myDataSource" PersonName="Joe"/>
...
</Window.Resources>
...
</Window>
若要绑定到 PersonName 属性,需要执行以下操作:
<TextBlock Text="{Binding Source={StaticResource myDataSource}, Path=PersonName}"/>
其结果是,TextBlock 将显示值“Joe”。