gpt4 book ai didi

c# - 如何以编程方式将 BindingExpression.Status 设置为 Active?

转载 作者:太空狗 更新时间:2023-10-29 23:33:02 24 4
gpt4 key购买 nike

我正在将 FrameworkElement 从 WPF 页面上的 StackPanel 转移到以编程方式创建的 StackPanel。在某个时候,我需要刷新绑定(bind)并获取属性值。

此时 FrameworkElement.DataContext 具有正确的值并且所有绑定(bind)表达式的 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();

}

}

从哪里获取对象的所有绑定(bind):

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);
}
}
}

最佳答案

您可以通过编程方式创建一个新的绑定(bind),这应该可以解决问题。

http://msdn.microsoft.com/en-us/library/ms752347.aspx#creating_a_binding

来自 MSDN 页面的示例

MyData myDataObject = new MyData(DateTime.Now);      
Binding myBinding = new Binding("MyDataProperty");
myBinding.Source = myDataObject;
myText.SetBinding(TextBlock.TextProperty, myBinding);

关于c# - 如何以编程方式将 BindingExpression.Status 设置为 Active?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12821107/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com