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 _sur开发者_运维技巧name;
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?
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}">
Did this often for Windows Phone projects but never had to derive a class for design time data when using the MVVM pattern.
View:
<phone:PhoneApplicationPage
d:DataContext="{d:DesignData ../DesignData/AvatarSampleData.xaml}" .../>
Design Time Data (AvatarSampleData.xaml):
<local:AvatarViewModel
xmlns="http:schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http:schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:YourNameSpace.ViewModels"
Name="Harald"
Surname="Flasch">
</local:AvatarViewModel>
hth, hfrmobile
精彩评论