Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set properties of a d:DesignInstance in XAML?

Tags:

wpf

xaml

I'm using the new d:DesignInstance feature of the 4.0 series WPF tools. Works great!

Only issue I'm having is: how can I set properties on the instance? Given something like this:

<Grid d:DataContext="{d:DesignInstance plugin:SamplePendingChangesViewModel, IsDesignTimeCreatable=True}"/>

How can I set properties on the viewmodel, aside from setting them in its default ctor or routing it through some other object initializer?

I gave this a try but VS gives errors on compile "d:DataContext was not found":

<Grid>
    <d:DataContext>
        <d:DesignInstance IsDesignTimeCreatable="True">
            <plugin:SamplePendingChangesViewModel ActiveTagIndex="2"/>
        </d:DesignInstance>
    </d:DataContext>

For the moment I'm going back to using a resource and 'd:DataContext={StaticResource SampleData}', where I can set the properties in the resource.

Is there a way to do it via a d:DesignInstance?

like image 346
scobi Avatar asked Apr 26 '10 20:04

scobi


1 Answers

As @jberger you should probably use d:DesignData instead of inlining a d:DataContext.

However you can set the d:DataContext inline in the xaml file as well, the secret is to use the correct class (DesignProperties) to qualify the d:DataContext property:

<d:DesignProperties.DataContext>
   <plugin:SamplePendingChangesViewModel ActiveTagIndex="2"/>
</d:DesignProperties.DataContext>

How do you know what class to qualify with? Mouse over a property that is set in attribute syntax and a tooltip will appear with the fully qualified property name.

Note also that im not using the d:DesignInstance markup exstension as its job specifically is to create a instance of a type that you provide the name for (or generate a proxy of that type if it cant be instanciated at design-time). Thats not what we want, we want to define the instance in inline xaml in this case.

Indeed, d:DesignData (also a markup extension) works much the same way, except that it looks for a xaml file and deserializes that to the actual instance to use instead of just using the default constructor.

Just for completeness i should also mention that you can use DesignData and DesignInstance with element syntax as well by using their full class names (xxxExtension):

<d:DesignProperties.DataContext>
  <d:DesignDataExtension Source="SampleData.xaml"></d:DesignDataExtension>
</d:DesignProperties.DataContext>

This is true for most markup exstensions but its not required to follow this naming convension (The Binding class is a notable exception) More info can be found here:

Markup Extensions and WPF XAML

like image 127
aL3891 Avatar answered Sep 28 '22 05:09

aL3891