views:

159

answers:

2

I was wondering if it's possible to write something like this:

<Window 
    ... xmlns definitions ...
    DataContext=<!--Create an instance here-->
></Window>

Instead of this:

<Window 
    ... xmlns definitions ...
>
   <Window.DataContext>
        <local:CustomViewModel />
   </Window.DataContext>
</Window>

I don't need workarounds to achieve the same effect, I'm just curious if the first kind of syntax is possible at all. I don't think that's the case but it's worth asking.

A: 

How about DataContext="{x:Static SomeClass.SomeProperty}" and then in SomeClass:

   public static object SomeProperty { get { return new object(); } }

Where object is the type you want to create. I am not sure if x:Static caches the object it once retrieved but if not, this would work. You could also try to sue ObjectDataProvider It allows you to call methods, constructors and properties.

bitbonk
+2  A: 

The only way I can see to this cleanly is to write your own MarkupExtension that uses Activator.CreateInstance (or your DI container) to create the VM, thus giving you a syntax like this:

<UserControl DataContext="{CreateNew local:CustomViewModel}"

HTH, Kent

Kent Boogaart
Worked like a charm, thanks!
RobSullivan