我正在将 WPF 页面上的 StackPanel 中的 FrameworkElement 转移到以编程方式创建的 StackPanel。在某个时候,我需要刷新绑定并获取属性值。
此时FrameworkElement.DataContext
具有正确的值并且BindingExpression.Status==BindingStatus.Unattached
适用于所有绑定表达式。我执行BindingExpression.UpdateTarget
,但属性值为空。
我找到了 BindingExpression.UpdateTarget() 的源代码:
public override void UpdateTarget()
{
if (Status == BindingStatus.Detached)
throw new InvalidOperationException(SR.Get(SRID.BindingExpressionIsDetached));
if (Worker != null)
{
Worker.RefreshValue(); // calls TransferValue
}
}
Worker 在内部覆盖 void 中获取实例BindingExpression.Activate()
。同样在 Activate() BindingExpression.Status 内部设置为 BindingStatus.Active。
我如何以编程方式启动执行BindingExpression.Activate()
并在此之后进行 UpdateTarget?
更新
这里的解决方案(谢谢,Olli):
public void UpdateAllBindingTargets( DependencyObject obj)
{
FrameworkElement visualBlock = obj as FrameworkElement;
if (visualBlock==null)
return;
if (visualBlock.DataContext==null)
return;
Object objDataContext = visualBlock.DataContext;
IEnumerable<KeyValuePair<DependencyProperty, BindingExpression>> allElementBinding = GetAllBindings(obj);
foreach (KeyValuePair<DependencyProperty, BindingExpression> bindingInfo in allElementBinding)
{
BindingOperations.ClearBinding(obj, bindingInfo.Key);
Binding myBinding = new Binding(bindingInfo.Value.ParentBinding.Path.Path);
myBinding.Source = objDataContext;
visualBlock.SetBinding(bindingInfo.Key, myBinding);
BindingOperations.GetBindingExpression(visualBlock, bindingInfo.Key).UpdateTarget();
}
}
在哪里获取对象的所有绑定:
public IEnumerable<KeyValuePair<DependencyProperty, BindingExpression>> GetAllBindings( DependencyObject obj)
{
var stack = new Stack<DependencyObject>();
stack.Push(obj);
while (stack.Count > 0)
{
var cur = stack.Pop();
var lve = cur.GetLocalValueEnumerator();
while (lve.MoveNext())
if (BindingOperations.IsDataBound(cur, lve.Current.Property))
{
KeyValuePair<DependencyProperty,BindingExpression> result=new KeyValuePair<DependencyProperty, BindingExpression>(lve.Current.Property,lve.Current.Value as BindingExpression);
yield return result;
}
int count = VisualTreeHelper.GetChildrenCount(cur);
for (int i = 0; i < count; ++i)
{
var child = VisualTreeHelper.GetChild(cur, i);
if (child is FrameworkElement)
stack.Push(child);
}
}
}