ListBox 的列表绑定远远不能满足我们实际工作中的需求,出于对灵活性、复用性以及代码精简的考虑,需要保证循环列表中的单个元素是独立的元素片段,类似Web中的局部视图。 这时候,使用用户控件会好很多。
DataTemplate:FruitInfoDT.xaml
<UserControl x:Class="MyUILib.FruitInfoDT"
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"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid>
<Grid.Resources>
<Style TargetType="{x:Type StackPanel}">
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="RenderTransform">
<Setter.Value>
<RotateTransform Angle="5"></RotateTransform>
</Setter.Value>
</Setter>
<Setter Property="Background" Value="#3B9CFB" />
</Trigger>
</Style.Triggers>
</Style>
</Grid.Resources>
<StackPanel Orientation="Vertical" Margin="10">
<Image Source="{Binding Img}" Width="96" Height="96" />
<TextBlock HorizontalAlignment="Center" Foreground="White" Text="{Binding Info}"/>
</StackPanel>
</Grid>
</UserControl>
XAML:
<Window.DataContext>
<local:VMTempTest/>
</Window.DataContext>
<StackPanel Margin="10,0,0,50" Orientation="Vertical" >
<TextBlock Text="用户控件模板列表" FontWeight="Bold" Margin="0,5,0,5" ></TextBlock>
<StackPanel HorizontalAlignment="Left" >
<ItemsControl ItemsSource="{Binding FiList}" HorizontalAlignment="Left" >
<ItemsControl.ItemTemplate>
<DataTemplate>
<local:FruitInfoDT />
</DataTemplate>
</ItemsControl.ItemTemplate>
<!-- 面板显示模板 -->
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel Orientation="Horizontal">
</WrapPanel>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</StackPanel>
</StackPanel>
Models:
public class FruitInfoViewModel : ObservableObject
{
private String img;
/// <summary>
/// 图片
/// </summary>
public String Img
{
get { return img; }
set { img = value; RaisePropertyChanged(() => Img); }
}
private String info;
/// <summary>
/// 信息
/// </summary>
public String Info
{
get { return info; }
set { info = value; RaisePropertyChanged(() => Info); }
}
}
ViewModel:
public class VMTempTest : ViewModelBase
{
public VMTempTest()
{
FiList = new ObservableCollection<FruitInfoViewModel>() {
new FruitInfoViewModel{ Img = "/MyWpfApp;component/Images/1.jpg", Info= "樱桃"},
new FruitInfoViewModel{ Img = "/MyWpfApp;component/Images/2.jpg", Info = "葡萄"}
};
}
private ObservableCollection<FruitInfoViewModel> fiList;
/// <summary>
/// 用户控件模板列表
/// </summary>
public ObservableCollection<FruitInfoViewModel> FiList
{
get { return fiList; }
set { fiList = value; RaisePropertyChanged(() => FiList); }
}
}
参考:
https://www.cnblogs.com/wzh2010/p/6425060.html