Search code examples
c#wpfstaticdatacontext

WPF assign static object to a DataContext in XAML


I'm in a situation where I have to use a static object as my DataContext. I have read many posts that recommends a Singleton class instead. However, I can't go this route due to design constraint.

I would like to assign a static object to my control DataContext as follows:

<UserControl.DataContext>
   <local:ViewModelA>
</UserControl.DataContext>

However it keeps telling me it is not usable object because it is not define a public constructor.

In my static view-model, I have a static constructor but it is not public due to C# constraints.

Thank you


Solution

  • You can only assign an instance of a (non-static) class to the DataContext property, not a class.

    You may however have a binding to a static property SomeProperty of your static class, like:

    <TextBlock Text="{Binding Path=(local:ViewModelA.SomeProperty)}" />