[英]How can I create a binding in code-behind that doesn't specify a Path?
I was answering another question about creating a binding in code-behind, and my original attempt at answering it was to post binding code that didn't specify a Path
. 我正在回答有关在代码隐藏中创建绑定的另一个问题 ,我最初尝试回答它是发布未指定
Path
绑定代码。 This binding compiles fine, however the value is never updated. 此绑定编译正常,但值永远不会更新。 If I change the binding to use a Path, it works fine.
如果我更改绑定以使用路径,它可以正常工作。
Why is this? 为什么是这样? And what is the correct way to create a binding in code-behind that doesn't have a Path?
在没有Path的代码隐藏中创建绑定的正确方法是什么? For example, how would I recreate
Value="{Binding }"
in code-behind? 例如,如何在代码隐藏中重新创建
Value="{Binding }"
?
Non-Working code: 非工作代码:
Binding b = new Binding();
b.Source = SomeInt;
b.Mode = BindingMode.OneWay;
MyProgressBar.SetBinding(ProgressBar.ValueProperty, b);
SomeInt = 50;
Working code: 工作代码:
Binding b = new Binding();
b.Source = this;
b.Path = new PropertyPath("SomeInt");
MyProgressBar.SetBinding(ProgressBar.ValueProperty, b);
SomeInt = 50;
The binding engine subscribes to INPC and DP -changes on the Source
object (and non-leaves on the Path
), and checks whether the Path
property/properties was/were changed. 绑定引擎订阅
Source
对象上的INPC和DP -changes(以及Path
上的非叶子),并检查Path
属性/属性是否已更改。 If there is no Path
there are no notifications. 如果没有
Path
,则没有通知。 A rather unfortunate drawback. 一个相当不幸的缺点。
(I might be oversimplifying the system a bit but the essence is that there are no updates to source-changes, they are not and cannot be monitored) (我可能会过度简化系统,但实质上是源更改没有更新,它们不会被监视,也不会被监视)
{Binding}
is equivalent to new Binding()
(no additional properties), this binding may update as there are events for DataContext
changes. {Binding}
等同于new Binding()
(没有其他属性),此绑定可能会更新,因为有DataContext
更改的事件。
Binding.Source
is typed as System.Object
. Binding.Source
被输入为System.Object
。 So when you do: 所以当你这样做时:
b.Source = SomeInt;
you're assigning a value type ( System.Int32
) into something of type System.Object
, which means you'll get a boxed copy of the original value. 您将值类型(
System.Int32
)分配给System.Object
类型的东西,这意味着您将获得原始值的盒装副本。
The boxed copy lives on the heap and has no relation to the original variable. 盒装副本存在于堆上,与原始变量无关。 When you modify the original variable, nothing happens to the boxed copy.
修改原始变量时,装箱副本没有任何反应。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.