tags:

views:

38

answers:

1

I have a class Wizard which creates a wizard with pages defined in the same project. The PageViewModel is separated from PageView. PageViewModel is an ordinary C# class derived from PageViewModelBase abstract class and PageView is a UserControl. In order to define a mapping between PageViewModel and PageView I wrote the following code for every page in my project:

 <Window.Resources>
    <DataTemplate DataType="{x:Type OurNewPageViewModel}">
      <OurNewPageView />
    </DataTemplate>
  </Window.Resources>

Now I want to add pages to wizard when the users’ code calls my Wizard’s constructor. It means to move Pages View and ViewModel to the user side. For instance, in order to create a wizard with one page user will write the following code: Wizard usersWizard = new Wizard(new usersViewModel(), new userView()); The problem is I don’t know how to provide the mapping between viewModel and View in my constructor. As far as I understand I can use two different approaches to solve this problem. First, to use FrameworkElementFactory but the following code doesn’t work:

        //let we have WelcomePageView wpview and WelcomePageViewModel wpviewmodel

        FrameworkElementFactory fef = new FrameworkElementFactory(wpview.GetType());
        DataTemplate dt = new DataTemplate();
        dt.DataType = wpview.GetType();

        dt.VisualTree = fef;

        base.Resources.Add(wpviewmodel.GetType(), dt);

Second, to use XamlReader. I can create a data template using it but I don’t know how to attach it to resources.

+1  A: 

In your code-behind to create the DataTemplate, there are a couple of errors:

  1. "dt.DataType = wpfView.GetType()" should be "dt.DataType = wpfviewmodel.GetType()"
  2. You should use a DataTemplateKey when adding the template to the ResourceDictionary.

So your code should be something like:

DataTemplate dt = new DataTemplate();
dt.DataType = typeof(PageViewModel);
FrameworkElementFactory fef = new FrameworkElementFactory(typeof(PageView));
dt.VisualTree = fef;
DataTemplateKey dtKey = new DataTemplateKey(typeof(PageViewModel));
this.Resources.Add(dtKey, dt);
karmicpuppet