从后面的代码多次调用SetBinding

时间:2011-09-12 23:57:58

标签: c# wpf binding multibinding

我有多个C#对象需要在属性更改时通知(属性属于FrameworkElement,如按钮或列表框)。

我谦卑地测试使用SetBinding方法绑定单个对象,如下所示:

// DepOb is my FrameworkElement
// DepPropDesc is the DependencyPropertyDescriptor

System.Windows.Data.Binding bind = new System.Windows.Data.Binding();
bind.Source = this;
bind.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
bind.Path = new PropertyPath("Value");
bind.Mode = ob.BindingMode;
DepOb.SetBinding(DepPropDesc.DependencyProperty, bind);

但是当我创建第二个对象并绑定它时,第一个对象不再被调用。如果我在行之间读取,该方法设置 绑定,所以前一个是刷新的,对吗?

MSDN讨论了一个“多绑定”对象,但我不知道如何“获取”存储在multibinding中的先前绑定,以便我可以向其添加新绑定。

我会继续搜索,但我想看看这里是否有人对我可能做错了什么有想法。

提前致谢!

Seb

1 个答案:

答案 0 :(得分:2)

在要绑定到第一个对象的第二个对象上设置绑定。当您在第二个对象上设置绑定时,可能已在第二个对象上设置的值将丢失,并且第一个对象的值可用于读取和写入(设置为TwoWay时)。

grid2.SetBinding(FrameworkElement.WidthProperty, new Binding("ActualWidth") { Source = grid1 });

因为你有一个grid3,你也可以这样做:

grid3.SetBinding(FrameworkElement.WidthProperty, new Binding("ActualWidth") { Source = grid1 });

在此示例中,WidthProperty是在FrameworkElement grid2上定义的静态readonly属性,grid3继承自FrameworkElement,因此他们可以使用此属性。

在你的代码中,你需要写这样的东西(注意模式上的BindingMode.OneWay)。

System.Windows.Data.Binding bind = new System.Windows.Data.Binding();       
bind.Source = this;       
bind.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;       
bind.Path = new PropertyPath("Value");       
bind.Mode = BindingMode.OneWay;
DepOb.SetBinding(DepObClass.WidthOrSomethingProperty, bind);

因为你绑定到一个实例(DepOb),你需要在它的类定义上定义实际属性(或使用一个继承的属性),如:

public static readonly DependencyProperty WidthOrSomethingProperty = DependencyProperty.Register("WidthOrSomething", typeof(double), typeof(DepObClass), null);

在DepObClass的实现中,您应该定义您的属性,如:

public double WidthOrSomething
{
     get { return GetValue(WidthOrSomethingProperty); }
     set { SetValue(WidthOrSomethingProperty, value); }
 }

希望有所帮助。