5

Does Visual Studio 2010 Visual Designer allow loading of data via external XML files during design time?

It appears that I can add it via d:DataContext, but I have a lot of data and it is easier to load it via XML. So is this possible?

kevindaub
  • 3,293
  • 6
  • 35
  • 46
  • what difference between using 'd:DataContext' and 'load via XML' are you looking for? Since d:DataContext will load your XML is there some other usage or functionality that you are looking for? – A.R. Mar 29 '11 at 12:48
  • My xml is loaded in via calls to my repository, so my datacontext is equal to that repository. So setting it to XML will not work in this case. – kevindaub Mar 29 '11 at 19:56

1 Answers1

2

One thing you can do is make a design time version of the repository (or other object) that you would use during runtime. A simple approach that I use on a regular basis goes like so.

in App.xaml:

<Application ...>
  <Application.Resources>
    <local:MyClass x:key="DesignData"/>
  </Application.Resources>
</Application>

then in your class constructor you can detect that you are in design mode and populate the data accordingly:

public class MyClass
{
  public MyClass()
  {
    bool isInDesign = DesignerProperties.GetIsInDesignMode(new DependencyObject());
    if (isInDesign)
    {
      // Load your XML + other setup routines.
    }

    // Normal ctor code.
  }
}

Finally, use this item and its data as your context.

<Window ...>
  <Grid d:DataContext="{StaticResource DesignData}">
    ...
  </Grid>
</Window>

This is probably the simplest approach that you can use to get complex design time data. Of course you may need to use a subclass of 'MyClass' or other approaches for very complicated scenarios, but it sounds like you know enough to handle that. Speaking from personal experience you can use this approach to make design data for any program state that you can think of, and you can even go so far as to pull live data from a DB if you want. Of course, the earlier you start thinking about design data in your application the easier it will be to actually make it work.

A.R.
  • 15,405
  • 19
  • 77
  • 123
  • That's exactly what I did. I just wasn't seeing any results at first. Thanks. – kevindaub Mar 31 '11 at 00:30
  • how do you load the XML file in design time? where do you put the file and how do you tell your designer to find it? – SelAromDotNet Feb 20 '13 at 05:38
  • The designer constructs instances of the classes, so you load it there. See in the above code block @ // Load your XML + other setup routines. ? You can load the file from any old place you want; a database, the filesystem, or embedded resource. – A.R. Feb 20 '13 at 14:07