简介

项目中经常会用到,同步两个控件的值,本文就简单列举两种方式来同步不同控件的两个Dependency Property。

 

示例

 

效果图:

[WPF系列]-使用Binding来同步不同控件的Dependency property

 

只使用C#代码:

//获取slider1的ValueDependency property的值
var binding = new Binding()
{
    ElementName = slider1.Name,
    UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged,
    Path = new PropertyPath("Value"),
    Mode = BindingMode.TwoWay
};


//将binding绑定到txtBox1的TextDependencyProperty的值
txtBox1.SetBinding(TextBox.TextProperty, binding);

 

这段小代码足以让大家对Binding有一点感性认识,但更多细节还是要查看MSDN。

 

只使用XAML代码:

  <Slider x:Name="slider1"   />
        <TextBox x:Name="txtBox1" Text="{ Binding ElementName=slider1, Path=Value}"  />

这段代码同上面C#的代码实现,更精简,可读性更高。

总结

综上所述,WPF里实现这两个属性值的同步,提供简单的方案。可以省去通过订阅事件如Valuechanged来实现slider的value和TextBox的text的值同步。

 

相关文章:

  • 2021-12-26
  • 2021-08-20
  • 2021-11-29
  • 2020-10-09
  • 2022-02-15
  • 2018-04-11
  • 2022-12-23
  • 2021-08-27
猜你喜欢
  • 2021-12-27
  • 2021-11-14
  • 2022-02-26
  • 2021-06-20
  • 2021-07-28
  • 2022-12-23
  • 2022-01-02
相关资源
相似解决方案