简体   繁体   中英

Howto bind Views to Viewmodel in a MVVM-Environment with XAML and WPF in C#

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 ?

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 :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM