界面元素之间需要联动,可以使用绑定
<StackPanel Orientation="Horizontal"> <TextBox x:Name="textBox" Width="50" Margin="10 " VerticalAlignment="Center"/> <Slider x:Name="mySlider" Minimum="10" Maximum="50" SmallChange="1" Margin="10" Width="300" VerticalAlignment="Center" IsSnapToTickEnabled="True" TickFrequency="5" Value="{Binding ElementName=textBox,Path=Text,Mode=TwoWay}"/> </StackPanel>
IsSnapToTickEnabled="True" 对齐到刻度
TickFrequency="5" 刻度间距5
Value="{Binding ElementName=textBox,Path=Text,Mode=TwoWay}" Slider(目标)的Value属性与textBox(源)的Text属性绑定,相互影响。
当然,也可以在CS中通过代码实现:
private void Window_Loaded(object sender, RoutedEventArgs e) { Binding bind = new Binding(); //创建对象 bind.Mode = BindingMode.TwoWay; //双向 bind.Source = this.textBox; //源textBox bind.Path = new PropertyPath("Text"); //textBox的Text属性 mySlider.SetBinding(Slider.ValueProperty, bind); //与mySlider的Value属性进行连接 }
运行的结果动态影响界面时,使用代码来实现。