0

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.

2 Answers 2

2

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}"
0
0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.