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

简介

项目中经常会用到,同步两个控件的值,本文就简单列举两种方式来同步不同控件的两个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的值同步。

原文地址:https://www.cnblogs.com/HQFZ/p/4260925.html