locked
Bindable data in XAML Designer RRS feed

  • Question

  • All,

     I have been designing a template for the items in a ListBox with a lot of data binding.  By default, there is no data to bind to while I am designing the XAML so the preview that I get is worthless.  The only way I know to test my markup is to run the app with data that I bind to the list box.

     I figure I must be missing something.  How do I tell the designer to use canned data to bind to the items, so I can see what it will look like with data?

     Thanks,

    Brian

     

    Friday, March 21, 2008 11:32 AM

Answers

  • Ok, after a bunch of slogging around, I finally found a way to do it.  There might be an easier way, but this is the way I found:

    Lets say that the data class you want to bind to looks like this:

        public class Data
        {
            public string FirstName { get; set; }
            public string LastName { get; set; }
            public int Age { get; set; }
        }

    You need to create a collection class which populates the data like this:

        public class DefaultData : ObservableCollection<Data>
        {
            public DefaultData()
            {
                base.Add(new Data() { FirstName = "Brian", LastName = "Genisio", Age = 30 });
                base.Add(new Data() { FirstName = "Cara", LastName = "Genisio", Age = 31 });
                base.Add(new Data() { FirstName = "Maia", LastName = "Genisio", Age = 1 });
            }
        }


    Now that that is complete, you need to make sure you add the namespace of your app.  My namespace in this example is DataGridPlay.

    <UserControl ... xmlns:l="clr-namespace:DataGridPlay" ...>

    Next, you need to define the resource for the UserControl with the name of your collection class:

        <UserControl.Resources>
            <l:DefaultData x:Key="MyDefaultData" />
        </UserControl.Resources>

    Finally, you can add this to your DataGrid or ListBox:

    <my:DataGrid ... ItemsSource="{Binding Source={StaticResource MyDefaultData}}" ...>

    WooHoo!!!!  All done.

     IS THERE AN EASIER WAY????????
     

    Friday, March 21, 2008 10:55 PM