I am transfering FrameworkElement from StackPanel on WPF Page to programmatically created StackPanel. At a certain point I need to refresh bindings and get property values.
At this point FrameworkElement.DataContext
has correct value and BindingExpression.Status==BindingStatus.Unattached
for all binding expressions. I execute BindingExpression.UpdateTarget
, but property values are empty.
I found source code for 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 gets instance in internal override void BindingExpression.Activate()
. Also inside Activate() BindingExpression.Status set to BindingStatus.Active.
How can I programmatically initiate execution for BindingExpression.Activate()
and make UpdateTarget after that?
Solution here (thanks, 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();
}
}
where getting all bindings for object:
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);
}
}
}
You can programmatically create a new binding, which should do the trick.
http://msdn.microsoft.com/en-us/library/ms752347.aspx#creating_a_binding
Example from the MSDN page
MyData myDataObject = new MyData(DateTime.Now);
Binding myBinding = new Binding("MyDataProperty");
myBinding.Source = myDataObject;
myText.SetBinding(TextBlock.TextProperty, myBinding);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With