1.普通的写法
<Canvas>
<TextBox Name="txtShow" Text="Hello" />
<TextBlock Canvas.Top="25">
<TextBlock.Text>
<Binding ElementName="txtShow" Path="Text" />
</TextBlock.Text>
</TextBlock>
</Canvas>
2.简化的写法.
<Canvas>
<TextBox Name="txtShow" Text="Hello" />
<TextBlock Canvas.Top="25"
Text="{Binding ElementName=txtShow, Path=Text}" />
</Canvas>
ElementName 属性(它用于绑定到一个控件),而不是使用 Source 属性。
3.NET 对象绑定:
<Window x:Class="WindowsApp2.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:c="clr-namespace:BindNonTextProperty"
Title="WindowsApp2" Height="300" Width="300"
>
<Grid>
<Grid.Resources>
<c:MyData x:Key="MyDataSource"/>
</Grid.Resources>
<Grid.DataContext>
<Binding Source="{StaticResource MyDataSource}"/>
</Grid.DataContext>
<Button Background="{Binding Path=ColorName}" Width="150" Height="30">I am bound to Green!</Button>
<Button Background="{Binding Source={StaticResource MyDataSource},Path=ColorNameT}" Width="20" Height="60">Red!</Button>
</Grid>
</Window>
类文件
using System;
namespace BindNonTextProperty
{
public partial class MyData
{
private string _data = "Green";
public string ColorName
{
get
{
return _data;
}
}
public string ColorNameT
{
get
{
return "Red";
}
}
}
}