1.Slider更改TextBlock的字体大小
1)在界面代码编写属性
<Grid> <StackPanel> <Slider Name="Slider1" Height="auto" Margin="10" IsSnapToTickEnabled="True" TickPlacement="TopLeft" TickFrequency="1" Minimum="1" Maximum="40" Value="10"></Slider> <TextBlock Name="TextBlock1" FontSize="{Binding ElementName=Slider1,Path=Value,Mode=TwoWay}">hello</TextBlock> <Button Click="Button_Click">set size=20</Button> </StackPanel> </Grid>
FontSize绑定Slider1的Value,模式为双向数据绑定
点击按钮、Slider1的值也会发生变化
private void Button_Click(object sender, RoutedEventArgs e) { this.TextBlock1.FontSize = 20; }
2)在后台代码中实现绑定属性
<Grid> <StackPanel> <Slider Name="Slider1" Height="auto" Margin="10" IsSnapToTickEnabled="True" TickPlacement="TopLeft" TickFrequency="1" Minimum="1" Maximum="40" Value="10"></Slider> <TextBlock Name="TextBlock1">hello</TextBlock> <Button Click="Button_Click">set size=20</Button> </StackPanel> </Grid>
后台代码
private void Button_Click(object sender, RoutedEventArgs e) { this.TextBlock1.FontSize = 20; } private void Window_Loaded(object sender, RoutedEventArgs e) { Binding binding = new Binding(); binding.Source = this.Slider1; binding.Path = new PropertyPath("Value"); binding.Mode = BindingMode.TwoWay; //双向绑定 this.TextBlock1.SetBinding(TextBlock.FontSizeProperty,binding);//绑定 }
2.继续上面的学习
加入一些新的东西扩展一下
<Grid> <StackPanel> <!--设置字体大小--> <Slider Name="Slider1" Height="auto" Margin="10" IsSnapToTickEnabled="True" TickPlacement="TopLeft" TickFrequency="1" Minimum="1" Maximum="40" Value="10"></Slider> <!--显示效果--> <TextBlock Name="TextBlock1" FontSize="{Binding ElementName=Slider1,Path=Value,Mode=TwoWay}" Background="{Binding ElementName=ListBox1,Path=SelectedItem.Tag}">hello</TextBlock> <!--设置字体大小--> <Button Click="Button_Click">set size=20</Button> <!--设置背景色--> <ListBox Name="ListBox1"> <ListBoxItem Tag="Red">Red</ListBoxItem> <ListBoxItem Tag="Blue">Blue</ListBoxItem> <ListBoxItem Tag="Yellow">Yellow</ListBoxItem> </ListBox> <!--设置字体大小--> <TextBox Name="TextBox1" Text="{Binding ElementName=Slider1,Path=Value,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"></TextBox> </StackPanel> </Grid>
原文:https://www.cnblogs.com/wskxy/p/11337138.html