1

Consider the following scenario:

WPF view:

d:DataContext="{d:DesignInstance vm:DesignViewModel, IsDesignTimeCreatable=True}"

ViewModel is located in a separate c# project:

internal class DesignViewModel : ViewModel 
{ /* create demo data in ctor */ }

ViewModel has this entry in AssemblyInfo:

[assembly: InternalsVisibleTo("WPF.Demo.View")]

Error message in XAML Designer:

  • The name "DesignViewModel" does not exist in the namespace "WPF.Demo.View".

Observations:

  • Everything works fine if I make DesignViewModel public, instead of internal. But, I'd like to keep it internal, for external consumers really shouldn't bother about design time stuff.
  • Everything works fine if I move DesignViewModel into the same assembly that holds the view. But, I'd like to keep view and ViewModel separate.
  • InternalsVisibleTo is set correctly, for I can access it from code behind in the view.

Question: How can I set d:DataContext to an internal class of another assembly?

sa.he
  • 1,391
  • 12
  • 25

1 Answers1

-1

You can't. By definition, when you mark an artifact as internal you are making it invisible from other assemblies.

Alternatively, you can expose a method on a public object, that makes what you want in the assembly's objects.

Regards,

  • 1
    Are you saying, that InternalsVisibleTo works only for C# but not for XAML? – sa.he Jan 14 '19 at 11:02
  • No, @sa.he, you're right that InternalsVisibleTo allows you to expose internal classes to outside assemblies. Very useful for unit testing. I don't have a direct answer for you now, but I'm thinking that you'd also have to expose internals to whatever assembly the WPF designer is using. i.e. it's not enough to expose internals of your VM project to your Views project, but you may also need to add an InternalsVisibleTo attribute to your VM project for whatever Microsoft project is the one doing the design time binding/XAML parsing. Just a guess that needs more research. – Andrew May 23 '20 at 21:09