Search code examples
wpfdata-bindinguser-controls

Update bindings for control created in code


I have created a UserControl, which has some values bound to its view model. I want to create an instance of that UserControl, provide it with a view model, and save it to an image without actually showing it on screen anywhere.

The problem is that when I create an instance of the UserControl and give it its view model, the bindings don't update. So the image that I am saving is the control without any data in it.

How can I force all the bindings to update for a user control that I am creating in code, without actually displaying it on screen?

Here is a short example I wrote:

UserControl1.xaml:

<Grid>
    <TextBlock Name="txt" Text="{Binding}" />
</Grid>

UserControl1.xaml.cs

public partial class UserControl1 : UserControl
{
    public UserControl1()
    {
        InitializeComponent();
    }

    internal string GetText()
    {
        return txt.Text;
    }
}

Test.cs

public void Test()
{
    UserControl1 uc1 = new UserControl1();
    uc1.DataContext = "Test";
    Console.WriteLine("The text is " + uc1.GetText());
}

I am expecting it to print out "The text is Test", but it actually prints out "The text is".


Solution

  • I managed to get around the problem by setting the DataContext before calling InitializeComponent. In order to do this, I created a new constructor for my user control that looks like this:

    public UserControl1(object viewModel)
    {
        DataContext = viewModel;
        InitializeComponent();
    }
    

    If I use this constructor, the bindings will work even if I never show the control on screen.