【问题标题】:Multiple calls to SetBinding from code behind从后面的代码多次调用 SetBinding
【发布时间】:2011-09-12 23:57:57
【问题描述】:

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

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

提前致谢!

赛博

【问题讨论】:

  • 这回答了你的问题吗?

标签: c# wpf binding multibinding


【解决方案1】:

绑定设置在要绑定到第一个对象的第二个对象上。当您在第二个对象上设置绑定时,可能已在第二个对象上设置的值会丢失,而第一个对象的值可用于读取和写入(当设置为 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); }
 }

希望对您有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    • 2015-09-26
    • 2019-09-06
    • 2011-12-02
    • 2012-04-24
    • 1970-01-01
    相关资源
    最近更新 更多