在silverlight的某个页面中,如果你想让控件A的宽度总是随着控件B的宽度变化,应该怎么办呢,答案就是元素属性绑定.
以下内容来自于http://silverlightchina.net/html/tips/2011/1225/12806.html
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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 <Slider Name="slider" 8 Value="90" 9 Grid.Row="0" 10 Maximum="180" 11 Margin="24" /> 12 <TextBlock Name="txtblk" 13 Text="{Binding ElementName=slider, Path=Value}" 14 Grid.Row="1" 15 FontSize="48" 16 HorizontalAlignment="Center" 17 VerticalAlignment="Center" />
注意上述代码中的TextBock的属性Text绑定代码,我们也可以用一下形式精简:Text=”{Binding Value,ElementName=slider}”。
另外还可以用下述另类的代码:Text=“{Binding ElementName=ContentPanel,Path=Children[0],Value}”。
值得注意的是可以不用该绑定语法,用属性元素语法也能办到:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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>
Silverlight数据绑定也可以用C#代码,当然也是易忽视或用到少的方式,但也要引起重视地!
1 Binding binding = new Binding(); 2 binding.ElementName = "slider"; 3 binding.Path = new PropertyPath("Value"); 4 //1.this.txtblk.SetBinding(TextBlock.TextProperty,binding); 5 //2.BindingOperations.SetBinding(this.txtblk,TextBlock.TextProperty,binding);
上述代码将名为slider的Silder元素的属性Value跟名为txtblk的TextBlock元素的属性Text绑定在了一起.