Search code examples
wpfdata-bindingdatatemplate.net-4.8

Resolve bindings after setting DataContext of control created with DataTemplate.LoadContent()


Given a XAML-declared data template:

<DataTemplate x:Key="MyDataTemplate">
    <TextBlock Text="{Binding DataValue}"/>
</DataTemplate>

And a class:

public class Model
{
    public string DataValue
    {
        get { return "TheDataValue"; }
    }
}

The following code does not do what I need:

var model = new Model();
var template = FindResource("MyDataTemplate") as DataTemplate;
var textBlock = template.LoadContent() as TextBlock;
textBlock.DataContext = model;

Eventually the binding from the DataTemplate gets resolved and the Text of the TextBlock shows "TheDataValue". But it does not happen quickly enough for some more code that needs to inspect the property. A breakpoint immediately after the last line of code shows textBlock.Text as having a value of "".

I have tried textBlock.UpdateTarget() and textBlock.InvalidateProperty(TextBlock.TextProperty) but neither seem to help.


Solution

  • Clearing and re-applying the databinding for the property on the dependency object seemed to do the trick:

    public static void Rebind(DependencyObject target, DependencyProperty property)
    {
        var binding = System.Windows.Data.BindingOperations.GetBinding(target, property);
        if(binding != null)
        {
            System.Windows.Data.BindingOperations.ClearBinding(target, property);
            System.Windows.Data.BindingOperations.SetBinding(target, property, binding);
        }
    }
    

    Calling that on the textBlock immediately after setting the DataContext immediately causes the binding to evaluate and property queries then return the expected, post-binding value "TheDataValue".