Search code examples
xamlwindows-phone-7genericswindows-phone-8expression-blend

Expression Blend WP -> Create design time data from class. Issues with Generics


Im trying to create sample data for WP project in Expression Blend. It works fine with simple classes, but not with custom generics classes. It can define structure of datasource, display correct structure of my ViewModel, but cannot generate values ie SampleData.xaml is empty.

How can I solve this, press some generate button or is there any other easy way to create design time data without writing everything manually?

I used a bit modified generic class NotifyTaskCompletion from here http://msdn.microsoft.com/en-us/magazine/dn605875.aspx and it is a root of problem. Here is result of generated data schema

enter image description here


Solution

  • The easiest thing to do is probably to create "dummy" types that are used by the designer. They would have the same public properties as your real types, but using concrete types and without any real code. They'd also have a different name. Since data-binding uses duck typing, the fact that the design-time object is a different type than the runtime object doesn't matter. For example, say your real class is:

    public class GenericObject<T>
    {
      public T Thing { get; set; }
    
      /* Lots of other complex code here... */
    }
    

    then you might also add:

    #if DEBUG
    public class GenericObjectDesigner
    {
      public string Thing { get; set; }
    
      /* No need for any complex code */
    }
    #endif
    

    Now in Blend, create a data source from the GenericObjectDesigner type and set the Thing property to be some string (eg, Lorum ipsum). You can now drag and drop that onto your design surface.

    And in your actual code, you use the non-Designer version of the class, eg:

    public MainPage()
    {
      InitializeComponent();
      this.DataContext = new GenericObject<int> { Thing = 42 };
    }
    

    This will work fine as long as VS is in Debug mode. In Release mode, the app will still compile and run correctly, but you will see errors about GenericObjectDesigner not existing in your XAML files (you can safely ignore them).