且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

什么时候应用数据绑定?

更新时间:2023-11-11 20:07:04

实际上并不那么简单,你不会直接回答这个问题。这取决于上下文。

It's not that simple actually, you won't get a straight answer for this question. It depends on the context.

这里有两个简单的例子:

Here are two simple examples :

如果有界属性由一个WPF控件不在ControlTemplate内,绑定很有可能首次被解析为 UpdateLayout 方法是第一次调用,如果DataContext已经设置。
如果DataContext未设置,它将在加载控件后尝试解析:请参阅下面的DataBindEngine.RequestRun()

If the bounded property is owned by a WPF control that is not inside a ControlTemplate, the binding will most likely be resolved for the first time when the UpdateLayout method is called for the first time, if the DataContext is already set. If the DataContext was not set, it will try to be resolved after the control is Loaded: see the DataBindEngine.RequestRun() below

private void RequestRun()
{
    base.Dispatcher.BeginInvoke(DispatcherPriority.DataBind, new DispatcherOperationCallback(this.Run), false);
    base.Dispatcher.BeginInvoke(DispatcherPriority.Loaded, new DispatcherOperationCallback(this.Run), true);
}

如果有界属性由ControlTemplate内的WPF控件拥有, ,它将在第一次布局过程中首次解决,这将触发 ApplyTemplate ,并导致解决绑定。

If the bounded property is owned by a WPF control that is inside a ControlTemplate however, it will be resolved for the first time during the first layouting pass that will trigger an ApplyTemplate and lead to resolving the binding.

这些只是具体的例子,如果你想完全了解绑定机制,你应该使用反射器来查看 MS.Internal.Data.DataBindEngine System.Windows.Data.BindindExpression 类。那些是在依赖属性使用绑定时负责推送正确数据的类。

Those are only specific examples, if you want to fully understand the binding mechanisms, you should use reflector to take a look at MS.Internal.Data.DataBindEngine and System.Windows.Data.BindindExpression classes. Those are the classes responsible for pushing the correct data when using bindings on dependency properties.