2

if I want to bind a view to a viewmodel I add the following to the resources of my XAML-Code:

<Window.Resources>
    <DataTemplate DataType="{x:Type MyViewModel}" >
        <views:MyView />
    </DataTemplate>
</Window.Resources> 

Is there any possibility to add the (viewmodel,view)-resource-entry to my resources dictonary in C#-Code?

The following two lines create the key and add it to the dictonary:

DataTemplateKey key = new DataTemplateKey(typeof(MyViewModel));
View.WindowName.Resources.Add(key, value);

But how can I create the value from the MyView which must have the type System.Windows.Baml2006.KeyRecord?

blacklwhite
  • 1,888
  • 1
  • 12
  • 17

1 Answers1

1

here is a sample on how you can create a datatepmlate with c# code.

ps: your question title should be something like how can a create a datatemplate with c# code. and this has btw nothing do to with mvvm. even more this code of course should not come into the viewmodel ;)

edit:

DataTemplate temp = new DataTemplate();
temp.DataType = typeof (MyViewModel);

FrameworkElementFactory fac = new FrameworkElementFactory(typeof(MyView));

temp.VisualTree = fac;

View.WindowName.Resources.Add(new DataTemplateKey(typeof(MyViewModel)), temp );

its much more easy in xaml :)

Community
  • 1
  • 1
blindmeis
  • 22,175
  • 7
  • 55
  • 74