wpfvisual-studio-2010design-time-data

Problem with design time data in WPF


Hi I try use my first design time data in wpf. I use tutorial from:

http://karlshifflett.wordpress.com/2009/10/21/visual-studio-2010-beta2-sample-data-project-templates/

http://karlshifflett.wordpress.com/2009/10/28/ddesigninstance-ddesigndata-in-visual-studio-2010-beta2/

I create simple data class, here is it:

public class Avatar:INotifyPropertyChanged
    {
        private string _name;
        private string _surname;

        public string Name
        {
            get { return _name; }
            set
            {
                _name = value;
                NotifyPropertyChanged("Name");
            }
        }

        public string Surname
        {
            get { return _surname; }
            set
            {
                _surname = value;
                NotifyPropertyChanged("Surname");
            }
        }


        public new event PropertyChangedEventHandler PropertyChanged;

        private void NotifyPropertyChanged(String info)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(info));
            }
        }

    }

Then I created sample data:

<TestForDesignTimeData:Avatar xmlns:TestForDesignTimeData="clr-namespace:TestForDesignTimeData" Name="John" Surname="Smith"/>

And try use design time data in wpf window:

<Window x:Class="TestForDesignTimeData.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:TestForDesignTimeData="clr-namespace:TestForDesignTimeData"
        mc:Ignorable="d" 
        Title="MainWindow" Height="350" Width="525">

        <StackPanel d:DataContext="{d:DesignInstance TestForDesignTimeData:Avatar}">
            <TextBlock Background="Yellow" Height="40" Width="250"   Text="{Binding Path=Name}"/>
            <TextBlock Background="Yellow" Height="40" Width="250"   Text="{Binding Path=Surname}"/>
    </StackPanel>
</Window>

But I see in designer empty textboxes. What I do bad?


Solution

  • You need to create a derived class from Avatar that will be used in the design time and define the sample data in the constructor of this class:

    public class AvatarDesignTime : Avatar
    {
       public AvatarDesignTime()
       {
          Name = "John";
          Surname = "Smith";
       }
    }
    

    Then you need to specify IsDesignTimeCreatable=True for the DesignInstance to enable instance creation in the design time (otherwise the type that you specify is used just for information about type members in order to setup bindings in the design time):

    <StackPanel d:DataContext="{d:DesignInstance TestForDesignTimeData:AvatarDesignTime, IsDesignTimeCreatable=True}">