| XAML开发入门之附加属性和绑定属性 |
|
| 来源:天极yesky 作者:轩辕南宫 加入时间:2006-12-8 访问次数:6 [大 中 小] |
|
而WPF中的绑定语法会根据源元素的属性值改变做出同样的响应,这种关联是一直持续的。在XAML中是使用Binding关键字来维续它们的一致性。
Binding元素的语法如下:
| 01 <Binding ElementName[元素名]=" …" Path[属性名]="…"/> | 我们用Binding关键字来表明这是一个绑定表达式语法,使用这种语法的实现都会在运行阶段进行实时的解析,以获得源元素的当前值。
在前面我们曾经创建了一个实例,就是你点击了多少次按钮,就会在按钮上的文本进行呈现。现在我们来使用绑定属性来扩展这个示例。我们可以为该页面添加一个TextBox元素,使得文本框中文本和一个TextBlock元素上的文本一致,也就是说将TextBox元素的Text属性和TextBlock元素的Text属性进行绑定,当你点击按钮时,就使得上述的两个文本信息同时发生变化,并且文本信息会显示改变的次数。
01 <Window 02 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 03 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 04 x:Class="SDKSample.Window1" 05 Width="460" 06 Height="200" 07 Title="BindDPtoDP"> 08 09 <DockPanel Background="White"> 10 11 <Button Click="btnChangeSource" Width="150" Height="30" 12 DockPanel.Dock="Top">Change Source Property</Button> 13 14 <TextBlock Name="Text1" DockPanel.Dock="Top" FontSize="12" 15 Height="30" Foreground="Green"> 16 <TextBlock.Text> 17 Click the Button to Change this Initial Text Value in this Source Element 18 </TextBlock.Text> 19 </TextBlock> 20 21 <TextBox DockPanel.Dock="Top" Height="30" Foreground="Blue"> 22 <TextBox.Text> 23 <Binding ElementName="Text1" Path="Text"/> 24 </TextBox.Text> 25 </TextBox> 26 27 </DockPanel> 28 29 </Window> | 在第23行代码处,可以看到我们在<TextBox.Text>从属属性中使用了绑定表达式语法来绑定TextBlock元素的Text属性.
对应的代码后置文件
01 using System; 02 using System.ComponentModel; 03 using System.Windows; 04 using System.Windows.Controls; 05 using System.Windows.Documents; 06 using System.Windows.Data; 07 using System.Windows.Media; 08 09 namespace SDKSample 10 { 11 /// <summary> 12 /// Window1: This is the class that encapsulates the code 13 /// "behind" the Window1.Xaml page. 14 /// </summary> 15 public partial class Window1 : Window 16 { 17 static int iCount = 0; 18 19 void btnChangeSource(object sender, RoutedEventArgs e) 20 { 21 iCount++; 22 Text1.Text = string.Format("New Text. Count={0}", iCount); 23 } 24 } 25 } | 效果下图所示,只要你点击按纽, TextBox元素的Text属性值和TextBlock元素的Text属性值都将发生变化.
|
|
|
|
|
|