假设我们有一个Person模型:
public class Person
{
public long Id { get; set; }
public string Name { get; set; }
public City City { get; set; }
}
我们有一个城市模型:
public class City
{
public long Id { get; set; }
public long ZipCode { get; set; }
public string Name { get; set; }
}
然后我们有一个WPF/XAML视图,像这样:
<Window
x:Class="WpfIssues.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:WpfIssues"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<ItemsControl Margin="20">
<d:ItemsControl.ItemsSource>
<x:Array Type="{x:Type local:Person}">
<local:Person Name="Thomas" Id="1" />
</x:Array>
</d:ItemsControl.ItemsSource>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="20" />
<ColumnDefinition Width="150" />
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0" Text="{Binding Id}" />
<TextBlock Grid.Column="1" Text="{Binding Name}" />
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
所有这些都给了我一个ItemsControl的设计时视图,其中包含一个Person项。
但是我不知道如何设置设计时属性值关于城市属性的Person类-像ZipCode城市和
?有人知道吗?
你可以使用标签语法:
<local:Person Name="Thomas" Id="1">
<local:Person.City>
<local:City Id="10" ZipCode ="zip"/>
</local:Person.City>
</local:Person>
或带有资源的属性语法(通常,使用仅在设计时使用的值不太实用)
<ItemsControl Margin="20">
<ItemsControl.Resources>
<local:City Id="10" ZipCode ="zip" x:Key="City10"/>
</ItemsControl.Resources>
<d:ItemsControl.ItemsSource>
<x:Array Type="{x:Type local:Person}">
<local:Person Name="Thomas" Id="1" City="{StaticResource City10}"/>
</x:Array>
</d:ItemsControl.ItemsSource>
这是典型的-在SO发布后10秒-我找到了解决方案:
<Window
x:Class="WpfIssues.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:WpfIssues"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<ItemsControl Margin="20">
<d:ItemsControl.ItemsSource>
<x:Array Type="{x:Type local:Person}">
<local:Person Name="Thomas" Id="1">
<local:Person.City>
<local:City Name="Holte" />
</local:Person.City>
</local:Person>
</x:Array>
</d:ItemsControl.ItemsSource>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="20" />
<ColumnDefinition Width="150" />
<ColumnDefinition Width="150" />
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0" Text="{Binding Id}" />
<TextBlock Grid.Column="1" Text="{Binding Name}" />
<TextBlock Grid.Column="2" Text="{Binding City.Name}" />
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>