2

我有多个 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 谈到了一个“多绑定”对象,但我不知道如何“获取”存储在多绑定中的先前绑定,以便我可以将新绑定附加到它。

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

提前致谢!

塞布

4

1 回答 1

2

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

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

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

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

在此示例中,WidthProperty 是在 FrameworkElement grid2 和 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); }
 }

希望有帮助。

于 2011-09-13T04:35:01.877 回答