WPF 数据模板绑定的几种方式

通过 StaticResource 引用

<Window x:Class="WpfApplication2.DataTemplateListWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfApplication2"
    Title="数据模板窗体" Height="300" Width="481" ResizeMode="NoResize" WindowStartupLocation="CenterScreen" Loaded="Window_Loaded">
<Window.Resources>
    <!--<DataTemplate DataType="{x:Type local:Goods}">
        <Border BorderThickness="1" BorderBrush="AliceBlue" CornerRadius="3">
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition />
                    <RowDefinition />
                </Grid.RowDefinitions>
                <TextBlock FontWeight="Bold" Text="{Binding Number}" />
                <TextBlock Grid.Row="1" Text="{Binding Name}" />
            </Grid>
        </Border>
    </DataTemplate>-->
    <DataTemplate x:Key="GoodsDataTemplate">
        <Border BorderThickness="1" BorderBrush="AliceBlue" CornerRadius="3">
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition />
                    <RowDefinition />
                </Grid.RowDefinitions>
                <TextBlock FontWeight="Bold" Text="{Binding Number}" />
                <TextBlock Grid.Row="1" Text="{Binding Name}" />
            </Grid>
        </Border>
    </DataTemplate>
</Window.Resources>
<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="200*" />
        <ColumnDefinition Width="auto" />
        <ColumnDefinition Width="250*" />
    </Grid.ColumnDefinitions>
    <GridSplitter Grid.Column="1" Width="3" VerticalAlignment="Stretch" HorizontalAlignment="Center" ShowsPreview="False" />
    <StackPanel Margin="5">
        <Button Content="获取数据" x:Name="BtnGetData" Margin="5" />
        <ListBox x:Name="lbGoods" ItemTemplate="{StaticResource GoodsDataTemplate}" Margin="5" HorizontalAlignment="Stretch" BorderBrush="SteelBlue">
            <!--<ListBox.ItemTemplate>
                <DataTemplate>
                    <Border BorderThickness="1" BorderBrush="AliceBlue" CornerRadius="3">
                        <Grid>
                            <Grid.RowDefinitions>
                                <RowDefinition />
                                <RowDefinition />
                            </Grid.RowDefinitions>
                            <TextBlock FontWeight="Bold" Text="{Binding Number}" />
                            <TextBlock Grid.Row="1" Text="{Binding Name}" />
                        </Grid>
                    </Border>
                </DataTemplate>
            </ListBox.ItemTemplate>-->
        </ListBox>
    </StackPanel>
    <StackPanel Margin="5" Grid.Column="2">
        <StackPanel Margin="5" Orientation="Horizontal">
            <Label Content="编号" />
            <TextBox Width="200" />
        </StackPanel>
        <StackPanel Margin="5" Orientation="Horizontal">
            <Label Content="名称" />
            <TextBox Width="200" />
        </StackPanel>
        <StackPanel Margin="5" Orientation="Horizontal">
            <Label Content="单价" />
            <TextBox Width="200" />
        </StackPanel>
        <StackPanel  Margin="5">
            <Label Content="描述" />
        </StackPanel>
        <StackPanel  Margin="5">
            <TextBox Width="235" HorizontalAlignment="Left" TextWrapping="Wrap" AcceptsReturn="False" Height="89" />
        </StackPanel>
    </StackPanel>
</Grid>
</Window>

通过指定模板的绑定数据的类型

<Window x:Class="WpfApplication2.DataTemplateListWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfApplication2"
    Title="数据模板窗体" Height="300" Width="481" ResizeMode="NoResize" WindowStartupLocation="CenterScreen" Loaded="Window_Loaded">
<Window.Resources>
    <DataTemplate DataType="{x:Type local:Goods}">
        <Border BorderThickness="1" BorderBrush="AliceBlue" CornerRadius="3">
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition />
                    <RowDefinition />
                </Grid.RowDefinitions>
                <TextBlock FontWeight="Bold" Text="{Binding Number}" />
                <TextBlock Grid.Row="1" Text="{Binding Name}" />
            </Grid>
        </Border>
    </DataTemplate>
    <!--<DataTemplate x:Key="GoodsDataTemplate">
        <Border BorderThickness="1" BorderBrush="AliceBlue" CornerRadius="3">
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition />
                    <RowDefinition />
                </Grid.RowDefinitions>
                <TextBlock FontWeight="Bold" Text="{Binding Number}" />
                <TextBlock Grid.Row="1" Text="{Binding Name}" />
            </Grid>
        </Border>
    </DataTemplate>-->
</Window.Resources>
<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="200*" />
        <ColumnDefinition Width="auto" />
        <ColumnDefinition Width="250*" />
    </Grid.ColumnDefinitions>
    <GridSplitter Grid.Column="1" Width="3" VerticalAlignment="Stretch" HorizontalAlignment="Center" ShowsPreview="False" />
    <StackPanel Margin="5">
        <Button Content="获取数据" x:Name="BtnGetData" Margin="5" />
        <ListBox x:Name="lbGoods" Margin="5" HorizontalAlignment="Stretch" BorderBrush="SteelBlue">
            <!--<ListBox.ItemTemplate>
                <DataTemplate>
                    <Border BorderThickness="1" BorderBrush="AliceBlue" CornerRadius="3">
                        <Grid>
                            <Grid.RowDefinitions>
                                <RowDefinition />
                                <RowDefinition />
                            </Grid.RowDefinitions>
                            <TextBlock FontWeight="Bold" Text="{Binding Number}" />
                            <TextBlock Grid.Row="1" Text="{Binding Name}" />
                        </Grid>
                    </Border>
                </DataTemplate>
            </ListBox.ItemTemplate>-->
        </ListBox>
    </StackPanel>
    <StackPanel Margin="5" Grid.Column="2">
        <StackPanel Margin="5" Orientation="Horizontal">
            <Label Content="编号" />
            <TextBox Width="200" />
        </StackPanel>
        <StackPanel Margin="5" Orientation="Horizontal">
            <Label Content="名称" />
            <TextBox Width="200" />
        </StackPanel>
        <StackPanel Margin="5" Orientation="Horizontal">
            <Label Content="单价" />
            <TextBox Width="200" />
        </StackPanel>
        <StackPanel  Margin="5">
            <Label Content="描述" />
        </StackPanel>
        <StackPanel  Margin="5">
            <TextBox Width="235" HorizontalAlignment="Left" TextWrapping="Wrap" AcceptsReturn="False" Height="89" />
        </StackPanel>
    </StackPanel>
</Grid>
</Window>

直接写在内部

<Window x:Class="WpfApplication2.DataTemplateListWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfApplication2"
    Title="数据模板窗体" Height="300" Width="481" ResizeMode="NoResize" WindowStartupLocation="CenterScreen" Loaded="Window_Loaded">
<Window.Resources>
    <!--<DataTemplate DataType="{x:Type local:Goods}">
        <Border BorderThickness="1" BorderBrush="AliceBlue" CornerRadius="3">
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition />
                    <RowDefinition />
                </Grid.RowDefinitions>
                <TextBlock FontWeight="Bold" Text="{Binding Number}" />
                <TextBlock Grid.Row="1" Text="{Binding Name}" />
            </Grid>
        </Border>
    </DataTemplate>
    <DataTemplate x:Key="GoodsDataTemplate">
        <Border BorderThickness="1" BorderBrush="AliceBlue" CornerRadius="3">
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition />
                    <RowDefinition />
                </Grid.RowDefinitions>
                <TextBlock FontWeight="Bold" Text="{Binding Number}" />
                <TextBlock Grid.Row="1" Text="{Binding Name}" />
            </Grid>
        </Border>
    </DataTemplate>-->
</Window.Resources>
<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="200*" />
        <ColumnDefinition Width="auto" />
        <ColumnDefinition Width="250*" />
    </Grid.ColumnDefinitions>
    <GridSplitter Grid.Column="1" Width="3" VerticalAlignment="Stretch" HorizontalAlignment="Center" ShowsPreview="False" />
    <StackPanel Margin="5">
        <Button Content="获取数据" x:Name="BtnGetData" Margin="5" />
        <ListBox x:Name="lbGoods" Margin="5" HorizontalAlignment="Stretch" BorderBrush="SteelBlue">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Border BorderThickness="1" BorderBrush="AliceBlue" CornerRadius="3">
                        <Grid>
                            <Grid.RowDefinitions>
                                <RowDefinition />
                                <RowDefinition />
                            </Grid.RowDefinitions>
                            <TextBlock FontWeight="Bold" Text="{Binding Number}" />
                            <TextBlock Grid.Row="1" Text="{Binding Name}" />
                        </Grid>
                    </Border>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </StackPanel>
    <StackPanel Margin="5" Grid.Column="2">
        <StackPanel Margin="5" Orientation="Horizontal">
            <Label Content="编号" />
            <TextBox Width="200" />
        </StackPanel>
        <StackPanel Margin="5" Orientation="Horizontal">
            <Label Content="名称" />
            <TextBox Width="200" />
        </StackPanel>
        <StackPanel Margin="5" Orientation="Horizontal">
            <Label Content="单价" />
            <TextBox Width="200" />
        </StackPanel>
        <StackPanel  Margin="5">
            <Label Content="描述" />
        </StackPanel>
        <StackPanel  Margin="5">
            <TextBox Width="235" HorizontalAlignment="Left" TextWrapping="Wrap" AcceptsReturn="False" Height="89" />
        </StackPanel>
    </StackPanel>
</Grid>
</Window>

模板选择器

<Window x:Class="WpfApplication2.DataTemplateListWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApplication2"
        Title="数据模板窗体" Height="300" Width="481" WindowStartupLocation="CenterScreen" Loaded="Window_Loaded">
    <Window.Resources>
        <!--<DataTemplate DataType="{x:Type local:Goods}">
            <Border BorderThickness="1" BorderBrush="AliceBlue" CornerRadius="3">
                <Grid>
                    <Grid.RowDefinitions>
                        <RowDefinition />
                        <RowDefinition />
                    </Grid.RowDefinitions>
                    <TextBlock FontWeight="Bold" Text="{Binding Number}" />
                    <TextBlock Grid.Row="1" Text="{Binding Name}" />
                </Grid>
            </Border>
        </DataTemplate>-->
        <DataTemplate x:Key="DefaultGoodsDataTemplate">
            <Border BorderThickness="1" BorderBrush="Blue" CornerRadius="3">
                <Grid Margin="3">
                    <Grid.RowDefinitions>
                        <RowDefinition />
                        <RowDefinition />
                    </Grid.RowDefinitions>
                    <TextBlock FontWeight="Bold" Text="{Binding Number}" />
                    <TextBlock Grid.Row="1" Text="{Binding Name}" />
                </Grid>
            </Border>
        </DataTemplate>
        <DataTemplate x:Key="RedGoodsDataTemplate">
            <Border BorderThickness="1" BorderBrush="Red" CornerRadius="3">
                <Grid Margin="3">
                    <Grid.RowDefinitions>
                        <RowDefinition />
                        <RowDefinition />
                    </Grid.RowDefinitions>
                    <TextBlock FontStyle="Italic" Text="{Binding Number}" />
                    <TextBlock Grid.Row="1" Text="{Binding Name}" />
                </Grid>
            </Border>
        </DataTemplate>
    </Window.Resources>
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="3*" />
            <ColumnDefinition Width="auto" />
            <ColumnDefinition Width="5*"/>
        </Grid.ColumnDefinitions>
        <GridSplitter Grid.Column="1" Width="3" VerticalAlignment="Stretch" HorizontalAlignment="Center" ShowsPreview="False" />
        <StackPanel Margin="5">
            <Button Content="获取数据" x:Name="BtnGetData" Margin="5" />

            <ListBox x:Name="lbGoods" Height="400" Margin="5" BorderBrush="SteelBlue" >
                <ListBox.ItemTemplateSelector>
                    <local:GoodsByUnitCostTemplateSelector />
                </ListBox.ItemTemplateSelector>
                <!--<ListBox.ItemTemplate>
                    <DataTemplate>
                        <Border BorderThickness="1" BorderBrush="AliceBlue" CornerRadius="3">
                            <Grid>
                                <Grid.RowDefinitions>
                                    <RowDefinition />
                                    <RowDefinition />
                                </Grid.RowDefinitions>
                                <TextBlock FontWeight="Bold" Text="{Binding Number}" />
                                <TextBlock Grid.Row="1" Text="{Binding Name}" />
                            </Grid>
                        </Border>
                    </DataTemplate>
                </ListBox.ItemTemplate>-->
            </ListBox>
        </StackPanel>
        <StackPanel Margin="5" Grid.Column="2">
            <StackPanel Margin="5" Orientation="Horizontal">
                <Label Content="编号" />
                <TextBox Width="200" />
            </StackPanel>
            <StackPanel Margin="5" Orientation="Horizontal">
                <Label Content="名称" />
                <TextBox Width="200" />
            </StackPanel>
            <StackPanel Margin="5" Orientation="Horizontal">
                <Label Content="单价" />
                <TextBox Width="200" />
            </StackPanel>
            <StackPanel  Margin="5">
                <Label Content="描述" />
            </StackPanel>
            <StackPanel  Margin="5">
                <TextBox Width="235" HorizontalAlignment="Left" TextWrapping="Wrap" AcceptsReturn="False" Height="89" />
            </StackPanel>
        </StackPanel>
    </Grid>
</Window>


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.Windows;

namespace WpfApplication2
{
    public class GoodsByUnitCostTemplateSelector : DataTemplateSelector
    {
        public override DataTemplate SelectTemplate(object item, DependencyObject container)
        {
            Goods goods = (Goods)item;
            Window win = Application.Current.MainWindow;

            if (goods.UnitCost < 10)
            {
                return (DataTemplate)win.FindResource("DefaultGoodsDataTemplate");
            }
            else
            {
                return (DataTemplate)win.FindResource("RedGoodsDataTemplate");
            }

            //return base.SelectTemplate(item, container);
        }
    }
}

ListBox 数据分组

<Window x:Class="WpfApplication2.DataTemplateListWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApplication2"
        Title="数据模板窗体" Height="300" Width="481" WindowStartupLocation="CenterScreen" Loaded="Window_Loaded">
    <Window.Resources>
        <!--<DataTemplate DataType="{x:Type local:Goods}">
            <Border BorderThickness="1" BorderBrush="AliceBlue" CornerRadius="3">
                <Grid>
                    <Grid.RowDefinitions>
                        <RowDefinition />
                        <RowDefinition />
                    </Grid.RowDefinitions>
                    <TextBlock FontWeight="Bold" Text="{Binding Number}" />
                    <TextBlock Grid.Row="1" Text="{Binding Name}" />
                </Grid>
            </Border>
        </DataTemplate>-->
        <DataTemplate x:Key="DefaultGoodsDataTemplate">
            <Border BorderThickness="1" BorderBrush="Blue" CornerRadius="3">
                <Grid Margin="3">
                    <Grid.RowDefinitions>
                        <RowDefinition />
                        <RowDefinition />
                    </Grid.RowDefinitions>
                    <TextBlock FontWeight="Bold" Text="{Binding Number}" />
                    <!--<TextBlock Grid.Row="1" Text="{Binding Name}" />-->
                    <TextBlock Grid.Row="1" Text="{Binding UnitCost}" />
                </Grid>
            </Border>
        </DataTemplate>
        <DataTemplate x:Key="RedGoodsDataTemplate">
            <Border BorderThickness="1" BorderBrush="Red" CornerRadius="3">
                <Grid Margin="3">
                    <Grid.RowDefinitions>
                        <RowDefinition />
                        <RowDefinition />
                    </Grid.RowDefinitions>
                    <TextBlock FontStyle="Italic" Text="{Binding Number}" />
                    <!--<TextBlock Grid.Row="1" Text="{Binding Name}" />-->
                    <TextBlock Grid.Row="1" Text="{Binding UnitCost}" />
                </Grid>
            </Border>
        </DataTemplate>
    </Window.Resources>
    <Grid >
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="3*" />
            <ColumnDefinition Width="auto" />
            <ColumnDefinition Width="5*"/>
        </Grid.ColumnDefinitions>
        <GridSplitter Grid.Column="1" Width="3" VerticalAlignment="Stretch" HorizontalAlignment="Center" ShowsPreview="False" />
        <StackPanel Margin="5">
            <Button Content="排序" x:Name="BtnSort" Click="BtnSort_Click" Margin="5" />

            <ListBox x:Name="lbGoods" Height="400" Margin="5" BorderBrush="SteelBlue" >
                <ListBox.GroupStyle>
                    <GroupStyle>
                        <GroupStyle.HeaderTemplate>
                            <DataTemplate>
                                <TextBlock Text="{Binding Name}" FontWeight="Bold" Foreground="White" Background="LightGreen" />
                            </DataTemplate>
                        </GroupStyle.HeaderTemplate>
                    </GroupStyle>
                </ListBox.GroupStyle>
                <ListBox.ItemTemplateSelector>
                    <local:GoodsByUnitCostTemplateSelector />
                </ListBox.ItemTemplateSelector>
                <!--<ListBox.ItemTemplate>
                    <DataTemplate>
                        <Border BorderThickness="1" BorderBrush="AliceBlue" CornerRadius="3">
                            <Grid>
                                <Grid.RowDefinitions>
                                    <RowDefinition />
                                    <RowDefinition />
                                </Grid.RowDefinitions>
                                <TextBlock FontWeight="Bold" Text="{Binding Number}" />
                                <TextBlock Grid.Row="1" Text="{Binding Name}" />
                            </Grid>
                        </Border>
                    </DataTemplate>
                </ListBox.ItemTemplate>-->
            </ListBox>
        </StackPanel>
        <StackPanel DataContext="{Binding ElementName=lbGoods,Path=SelectedItem}" Margin="5" Grid.Column="2">
            <StackPanel Margin="5" Orientation="Horizontal">
                <Label Content="编号" />
                <TextBox Width="200" Text="{Binding Number}" />
            </StackPanel>
            <StackPanel Margin="5" Orientation="Horizontal">
                <Label Content="名称" />
                <TextBox Width="200" Text="{Binding Name}" />
            </StackPanel>
            <StackPanel Margin="5" Orientation="Horizontal">
                <Label Content="单价" />
                <TextBox Width="200" Text="{Binding UnitCost}" />
            </StackPanel>
            <StackPanel  Margin="5">
                <Label Content="描述" />
            </StackPanel>
            <StackPanel  Margin="5">
                <TextBox Width="235" Text="{Binding Description}" HorizontalAlignment="Left" TextWrapping="Wrap" AcceptsReturn="False" Height="89" />
            </StackPanel>
        </StackPanel>
    </Grid>
</Window>


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Threading;
using System.Collections.ObjectModel;
using System.ComponentModel;

namespace WpfApplication2
{
    /// <summary>
    /// DataTemplateListWindow.xaml 的交互逻辑
    /// </summary>
    public partial class DataTemplateListWindow : Window
    {

        public ObservableCollection<Goods> goodsList { get;set; }

        public DataTemplateListWindow()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            this.Dispatcher.BeginInvoke((ThreadStart)delegate() {
                List<Goods> list = new List<Goods> { 
                    new Goods{ Number="BLKDJS", Name="2B 铅笔", UnitCost=20, Description="中华牌 2B 铅笔,您值得拥有"},
                    new Goods{ Number="xxssddf", Name="HB 铅笔", UnitCost=2, Description="中华牌 HB 铅笔,您值得拥有"},
                    new Goods{ Number="BLKDJS", Name="2B 铅笔", UnitCost=6, Description="中华牌 2B 铅笔,您值得拥有"},
                    new Goods{ Number="xxssddf", Name="HB 铅笔", UnitCost=7, Description="中华牌 HB 铅笔,您值得拥有"},
                    new Goods{ Number="BLKDJS", Name="2B 铅笔", UnitCost=7, Description="中华牌 2B 铅笔,您值得拥有"},
                    new Goods{ Number="xxssddf", Name="HB 铅笔", UnitCost=13, Description="中华牌 HB 铅笔,您值得拥有"},
                    new Goods{ Number="BLKDJS", Name="2B 铅笔", UnitCost=43, Description="中华牌 2B 铅笔,您值得拥有"},
                    new Goods{ Number="xxssddf", Name="HB 铅笔", UnitCost=10, Description="中华牌 HB 铅笔,您值得拥有"}
                };

                this.lbGoods.ItemsSource = new ObservableCollection<Goods>(list);

            });
        }

        private void BtnSort_Click(object sender, RoutedEventArgs e)
        {

            ICollectionView view = CollectionViewSource.GetDefaultView(lbGoods.ItemsSource);

            //排序
            view.SortDescriptions.Add(new SortDescription("UnitCost", ListSortDirection.Ascending));

            //分组
            PriceRangeProductGrouper grouper = new PriceRangeProductGrouper();
            grouper.GroupInterval = 10;
            view.GroupDescriptions.Add(new PropertyGroupDescription("UnitCost", grouper));
        }

    }

    public class Goods
    {
        public string Number { get; set; }
        public string Name { get; set; }
        public decimal UnitCost { get; set; }
        public string Description { get; set; }
    }

    public class PriceRangeProductGrouper:IValueConverter
    {

        public int GroupInterval { get; set; }

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            decimal price = (decimal)value;
            if (price < GroupInterval)
            {
                return string.Format(culture, "小于 {0:C}", GroupInterval);
            }
            else
            {
                int interval = (int)price / GroupInterval;
                int lowLimit = interval * GroupInterval;
                int upperLimit = (interval + 1) * GroupInterval;

                return string.Format(culture, "{0:C} ~ {1:C}", lowLimit, upperLimit);
            }

        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

}

申明式创建视图(分组和排序)

<Window x:Class="WpfApplication2.DataTemplateListWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApplication2"
        xmlns:component="clr-namespace:System.ComponentModel;assembly=WindowsBase"
        Title="数据模板窗体" Height="300" Width="481" WindowStartupLocation="CenterScreen" Loaded="Window_Loaded">
    <Window.Resources>
        <!--<DataTemplate DataType="{x:Type local:Goods}">
            <Border BorderThickness="1" BorderBrush="AliceBlue" CornerRadius="3">
                <Grid>
                    <Grid.RowDefinitions>
                        <RowDefinition />
                        <RowDefinition />
                    </Grid.RowDefinitions>
                    <TextBlock FontWeight="Bold" Text="{Binding Number}" />
                    <TextBlock Grid.Row="1" Text="{Binding Name}" />
                </Grid>
            </Border>
        </DataTemplate>-->
        <local:PriceRangeProductGrouper x:Key="Price10Grouper" GroupInterval="10" />
        <CollectionViewSource x:Key="GroupByRangeView">
            <CollectionViewSource.SortDescriptions>
                <component:SortDescription PropertyName="UnitCost" Direction="Ascending" />
            </CollectionViewSource.SortDescriptions>
            <CollectionViewSource.GroupDescriptions>
                <PropertyGroupDescription PropertyName="UnitCost" Converter="{StaticResource Price10Grouper}" />
            </CollectionViewSource.GroupDescriptions>
        </CollectionViewSource>
        <DataTemplate x:Key="DefaultGoodsDataTemplate">
            <Border BorderThickness="1" BorderBrush="Blue" CornerRadius="3">
                <Grid Margin="3">
                    <Grid.RowDefinitions>
                        <RowDefinition />
                        <RowDefinition />
                    </Grid.RowDefinitions>
                    <TextBlock FontWeight="Bold" Text="{Binding Number}" />
                    <!--<TextBlock Grid.Row="1" Text="{Binding Name}" />-->
                    <TextBlock Grid.Row="1" Text="{Binding UnitCost}" />
                </Grid>
            </Border>
        </DataTemplate>
        <DataTemplate x:Key="RedGoodsDataTemplate">
            <Border BorderThickness="1" BorderBrush="Red" CornerRadius="3">
                <Grid Margin="3">
                    <Grid.RowDefinitions>
                        <RowDefinition />
                        <RowDefinition />
                    </Grid.RowDefinitions>
                    <TextBlock FontStyle="Italic" Text="{Binding Number}" />
                    <!--<TextBlock Grid.Row="1" Text="{Binding Name}" />-->
                    <TextBlock Grid.Row="1" Text="{Binding UnitCost}" />
                </Grid>
            </Border>
        </DataTemplate>
    </Window.Resources>
    <Grid >
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="3*" />
            <ColumnDefinition Width="auto" />
            <ColumnDefinition Width="5*"/>
        </Grid.ColumnDefinitions>
        <GridSplitter Grid.Column="1" Width="3" VerticalAlignment="Stretch" HorizontalAlignment="Center" ShowsPreview="False" />
        <StackPanel Margin="5">
            <Button Content="排序" x:Name="BtnSort" Click="BtnSort_Click" Margin="5" />

            <ListBox ItemsSource="{Binding Source={StaticResource GroupByRangeView}}" x:Name="lbGoods" Height="400" Margin="5" BorderBrush="SteelBlue" >
                <ListBox.GroupStyle>
                    <GroupStyle>
                        <GroupStyle.HeaderTemplate>
                            <DataTemplate>
                                <TextBlock Text="{Binding Name}" FontWeight="Bold" Foreground="White" Background="LightGreen" />
                            </DataTemplate>
                        </GroupStyle.HeaderTemplate>
                    </GroupStyle>
                </ListBox.GroupStyle>
                <ListBox.ItemTemplateSelector>
                    <local:GoodsByUnitCostTemplateSelector />
                </ListBox.ItemTemplateSelector>
                <!--<ListBox.ItemTemplate>
                    <DataTemplate>
                        <Border BorderThickness="1" BorderBrush="AliceBlue" CornerRadius="3">
                            <Grid>
                                <Grid.RowDefinitions>
                                    <RowDefinition />
                                    <RowDefinition />
                                </Grid.RowDefinitions>
                                <TextBlock FontWeight="Bold" Text="{Binding Number}" />
                                <TextBlock Grid.Row="1" Text="{Binding Name}" />
                            </Grid>
                        </Border>
                    </DataTemplate>
                </ListBox.ItemTemplate>-->
            </ListBox>
        </StackPanel>
        <StackPanel DataContext="{Binding ElementName=lbGoods,Path=SelectedItem}" Margin="5" Grid.Column="2">
            <StackPanel Margin="5" Orientation="Horizontal">
                <Label Content="编号" />
                <TextBox Width="200" Text="{Binding Number}" />
            </StackPanel>
            <StackPanel Margin="5" Orientation="Horizontal">
                <Label Content="名称" />
                <TextBox Width="200" Text="{Binding Name}" />
            </StackPanel>
            <StackPanel Margin="5" Orientation="Horizontal">
                <Label Content="单价" />
                <TextBox Width="200" Text="{Binding UnitCost}" />
            </StackPanel>
            <StackPanel  Margin="5">
                <Label Content="描述" />
            </StackPanel>
            <StackPanel  Margin="5">
                <TextBox Width="235" Text="{Binding Description}" HorizontalAlignment="Left" TextWrapping="Wrap" AcceptsReturn="False" Height="89" />
            </StackPanel>
        </StackPanel>
    </Grid>
</Window>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Threading;
using System.Collections.ObjectModel;
using System.ComponentModel;

namespace WpfApplication2
{
    /// <summary>
    /// DataTemplateListWindow.xaml 的交互逻辑
    /// </summary>
    public partial class DataTemplateListWindow : Window
    {

        public ObservableCollection<Goods> goodsList { get;set; }

        public DataTemplateListWindow()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            this.Dispatcher.BeginInvoke((ThreadStart)delegate() {
                List<Goods> list = new List<Goods> { 
                    new Goods{ Number="BLKDJS", Name="2B 铅笔", UnitCost=20, Description="中华牌 2B 铅笔,您值得拥有"},
                    new Goods{ Number="xxssddf", Name="HB 铅笔", UnitCost=2, Description="中华牌 HB 铅笔,您值得拥有"},
                    new Goods{ Number="BLKDJS", Name="2B 铅笔", UnitCost=6, Description="中华牌 2B 铅笔,您值得拥有"},
                    new Goods{ Number="xxssddf", Name="HB 铅笔", UnitCost=7, Description="中华牌 HB 铅笔,您值得拥有"},
                    new Goods{ Number="BLKDJS", Name="2B 铅笔", UnitCost=7, Description="中华牌 2B 铅笔,您值得拥有"},
                    new Goods{ Number="xxssddf", Name="HB 铅笔", UnitCost=13, Description="中华牌 HB 铅笔,您值得拥有"},
                    new Goods{ Number="BLKDJS", Name="2B 铅笔", UnitCost=43, Description="中华牌 2B 铅笔,您值得拥有"},
                    new Goods{ Number="xxssddf", Name="HB 铅笔", UnitCost=10, Description="中华牌 HB 铅笔,您值得拥有"}
                };

                //this.lbGoods.ItemsSource = new ObservableCollection<Goods>(list);

                CollectionViewSource viewSource = (CollectionViewSource)this.FindResource("GroupByRangeView");

                viewSource.Source = list;


            });
        }

        private void BtnSort_Click(object sender, RoutedEventArgs e)
        {

            ICollectionView view = CollectionViewSource.GetDefaultView(lbGoods.ItemsSource);

            //排序
            view.SortDescriptions.Add(new SortDescription("UnitCost", ListSortDirection.Ascending));

            //分组
            PriceRangeProductGrouper grouper = new PriceRangeProductGrouper();
            grouper.GroupInterval = 10;
            view.GroupDescriptions.Add(new PropertyGroupDescription("UnitCost", grouper));
        }

    }

    public class Goods
    {
        public string Number { get; set; }
        public string Name { get; set; }
        public decimal UnitCost { get; set; }
        public string Description { get; set; }
    }

    public class PriceRangeProductGrouper:IValueConverter
    {

        public int GroupInterval { get; set; }

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            decimal price = (decimal)value;
            if (price < GroupInterval)
            {
                return string.Format(culture, "小于 {0:C}", GroupInterval);
            }
            else
            {
                int interval = (int)price / GroupInterval;
                int lowLimit = interval * GroupInterval;
                int upperLimit = (interval + 1) * GroupInterval;

                return string.Format(culture, "{0:C} ~ {1:C}", lowLimit, upperLimit);
            }

        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

}

知识共享许可协议
《WPF 数据模板绑定的几种方式》 常伟华 创作。
本作品采用知识共享署名-相同方式共享 4.0 国际许可协议 | 3.0 中国大陆许可协议进行许可。

站内公告

A PHP Error was encountered

Severity: Core Warning

Message: PHP Startup: zip: Unable to initialize module Module compiled with module API=20060613 PHP compiled with module API=20090626 These options need to match

Filename: Unknown

Line Number: 0

Backtrace: