Данные времени проектирования для таблицы данных в xaml
Это может быть глупым вопросом, но возможно ли определить некоторые примеры данных как DataContext, чтобы увидеть мой DataTemplate в DesignView?
В настоящий момент мне всегда нужно запускать приложение, чтобы увидеть, работают ли мои изменения.
Например, со следующим кодом DesignView просто показывает пустой список:
<ListBox x:Name="standardLayoutListBox" ItemsSource="{Binding myListboxItems}">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Label Grid.Column="0" Content="{Binding text1}" />
<Label Grid.Column="1" Content="{Binding text2}" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
2 ответа
public class MyMockClass
{
public MyMockClass()
{
MyListBoxItems.Add(new MyDataClass() { text1 = "test text 1", text2 = "test text 2" });
MyListBoxItems.Add(new MyDataClass() { text1 = "test text 3", text2 = "test text 4" });
}
public ObservableCollection<MyDataClass> MyListBoxItems { get; set; }
}
public class MyDataClass
{
public string text1 { get; set; }
public string text2 { get; set; }
}
В твоем XAML
Добавить объявление пространства имен
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
Добавьте фиктивный контекст данных в ресурсы окна / управления
<UserControl.Resources>
<local:MyMockClass x:Key="DesignViewModel"/>
</UserControl.Resources>
Затем измените свой ListBox для ссылки на объект времени разработки
<ListBox x:Name="standardLayoutListBox"
d:DataContext="{Binding Source={StaticResource DesignViewModel}}"
ItemsSource="{Binding MyListBoxItems}">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Label Grid.Column="0" Content="{Binding text1}" />
<Label Grid.Column="1" Content="{Binding text2}" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Когда вы работаете в дизайнере, вам не придется возиться с моделями представления, поэтому я думаю, что лучше включить данные времени разработки в xaml, а не в C #, взгляните на это простое представление POCO
<ListView ItemsSource="{Binding Items}">
<d:ListView.ItemsSource>
<x:Array Type="{x:Type models:Monkey}">
<models:Monkey Name="Baboon" Location="Africa and Asia"/>
<models:Monkey Name="Capuchin Monkey" Location="Central and South America"/>
<models:Monkey Name="Blue Monkey" Location="Central and East Africa"/>
</x:Array>
</d:ListView.ItemsSource>
<ListView.ItemTemplate>
<DataTemplate x:DataType="models:Monkey">
<TextCell Text="{Binding Name}"
Detail="{Binding Location}" />
</DataTemplate>
</ListView.ItemTemplate>