<Window x:Class="WpfApp.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:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp"
mc:Ignorable="d"
WindowStartupLocation="CenterScreen"
ResizeMode="CanMinimize"
Title="MainWindow" Height="350" Width="625">
<Window.Resources>
<!--直接路劲引用,单个程序集里面其实可以省略路径前面/WpfApp;component/一截-->
<ResourceDictionary Source="/WpfApp;component/Assist/Dictionary1.xaml"/>
</Window.Resources>
<!--窗体内容-->
<StackPanel Orientation="Horizontal" Margin="5">
<UserControl ContentTemplate="{StaticResource carDetailViewTemplate}" Content="{Binding SelectedItem, ElementName=listBoxCars}"/>
<ListBox x:Name="listBoxCars" Width="180" Margin="5 0" ItemTemplate="{StaticResource carListItemViewTemplate}"/>
</StackPanel>
</Window>
<ResourceDictionary Source="/WpfApp;component/Assist/Dictionary1.xaml"/>
引用的是数据模板在项目中的文件路径。和控件模板的方式差不多。
Dictionary1.xaml:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApp">
<!--Converter-->
<local:AutomakerToLogoPathConverter x:Key="a2l"/>
<local:NameToPhotoPathConverter x:Key="n2p"/>
<!--DataTemplate for Detail View-->
<DataTemplate x:Key="carDetailViewTemplate">
<Border BorderBrush="Black" BorderThickness="1" CornerRadius="6">
<StackPanel Margin="5">
<Image Width="400" Height="250" Stretch="Fill" Source="{Binding Name, Converter={StaticResource n2p}}"/>
<StackPanel Orientation="Horizontal" Margin="5 0">
<TextBlock Text="品牌:" FontWeight="Bold" FontSize="20"/>
<TextBlock Text="{Binding Name}" FontSize="20" Margin="5 0"/>
</StackPanel>
<StackPanel Orientation="Horizontal" Margin="5 0">
<TextBlock Text="制造商:" FontWeight="Bold"/>
<TextBlock Text="{Binding Automaker}" />
<TextBlock Text="年份:" FontWeight="Bold" Margin="10 0 0 0"/>
<TextBlock Text="{Binding Year}" />
<TextBlock Text="最高速度:" FontWeight="Bold" Margin="10 0 0 0"/>
<TextBlock Text="{Binding TopSpeed, StringFormat={}{0}Km/h}" />
</StackPanel>
</StackPanel>
</Border>
</DataTemplate>
<!--DataTemplate for Item View-->
<DataTemplate x:Key="carListItemViewTemplate">
<Grid Margin="2">
<StackPanel Orientation="Horizontal">
<Image Source="{Binding Automaker, Converter={StaticResource a2l}}" Grid.RowSpan="3" Width="64" Height="64"/>
<StackPanel Margin="5 10">
<TextBlock Text="{Binding Name}" FontSize="16" FontWeight="Bold"/>
<TextBlock Text="{Binding Year}" FontSize="14"/>
</StackPanel>
</StackPanel>
</Grid>
</DataTemplate>
</ResourceDictionary>