现在的位置: 首页 > 综合 > 正文

Silverlight数据绑定–元素属性绑定

2012年03月21日 ⁄ 综合 ⁄ 共 1831字 ⁄ 字号 评论关闭

对于程序员来讲,很多知识用代码比用文字更能说明问题,所以在介绍Silverlight数据绑定这一特性的时候,我用以下代码作为今后学习的备忘录把……

望有关群众勿喷啊。。。。。。

 1:  <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
 2:              <Grid.RowDefinitions>
 3:                  <RowDefinition Height="*" />
 4:                  <RowDefinition Height="*" />
 5:                  <RowDefinition Height="*" />
 6:              </Grid.RowDefinitions>
 7:  
 8:              <Slider Name="slider" 
 9:  Value="90"
10:  Grid.Row="0"
11:  Maximum="180"
12:  Margin="24" />
13:  
14:              <TextBlock Name="txtblk" 
15:  Text="{Binding ElementName=slider, Path=Value}"
16:  Grid.Row="1"
17:  FontSize="48"
18:  HorizontalAlignment="Center"
19:  VerticalAlignment="Center" />
20:  

 

注意上述代码中的TextBock的属性Text绑定代码,我们也可以用一下形式精简:Text=”{Binding Value,ElementName=slider}”。

另外还可以用下述另类的代码:Text=“{Binding ElementName=ContentPanel,Path=Children[0],Value}”。

值得注意的是可以不用该绑定语法,用属性元素语法也能办到:

 1:   <TextBlock Name="txtblk" 
 2:  Grid.Row="1"
 3:  FontSize="48"
 4:  HorizontalAlignment="Center"
 5:  VerticalAlignment="Center" >
 6:                  <TextBlock.Text>
 7:                      <Binding ElementName="slider" Path="Value"></Binding>
 8:                  </TextBlock.Text>
 9:              </TextBlock>
10:  
11:  

 

Silverlight数据绑定也可以用C#代码,当然也是易忽视或用到少的方式,但也要引起重视地!

 1:  using System;
 2:  using System.Collections.Generic;
 3:  using System.Linq;
 4:  using System.Net;
 5:  using System.Windows;
 6:  using System.Windows.Controls;
 7:  using System.Windows.Documents;
 8:  using System.Windows.Input;
 9:  using System.Windows.Media;
10:  using System.Windows.Media.Animation;
11:  using System.Windows.Shapes;
12:  using Microsoft.Phone.Controls;
13:  using System.Windows.Data;
14:   
15:  namespace SliderBindings
16:  {
17:      public partial class MainPage : PhoneApplicationPage
18:  {
19:          // Constructor
20:  public MainPage()
21:          {
22:              InitializeComponent();
23:              Binding binding = new Binding();
24:              binding.ElementName = "slider";
25:              binding.Path = new PropertyPath("Value");
26:              //1.this.txtblk.SetBinding(TextBlock.TextProperty,binding);
27:              //2.BindingOperations.SetBinding(this.txtblk,TextBlock.TextProperty,binding);
28:  }
29:      }
30:  }
31:   

 

上述代码将名为slider的Silder元素的属性Value跟名为txtblk的TextBlock元素的属性Text绑定在了一起……

抱歉!评论已关闭.