介紹ItemTemplate用法以及在ItemTemplate模闆中使用ListBoxItem屬性的方法。
實作如下效果(點選某一項的時候該項圖檔進行放大):

C#代碼:
using System.Collections.ObjectModel;
using System.Windows;
namespace ListBox用法
{
/// <summary>
/// MainWindow.xaml 的互動邏輯
/// </summary>
public partial class MainWindow : Window
{
public ObservableCollection<Person> PList { get; set; }
public MainWindow()
{
InitializeComponent();
PList = new ObservableCollection<Person>();
PList.Add(new Person { IsFemale = true, Name = "小紅" });
PList.Add(new Person { IsFemale = false, Name = "小明" });
this.DataContext = this;
}
}
public class Person
{
public bool IsFemale { get; set; }
public string Name { get; set; }
}
}
XAML代碼:
<Window x:Class="ListBox用法.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:ListBox用法"
Title="MainWindow" Height="350" Width="525">
<ListBox ItemsSource="{Binding PList}">
<ListBox.ItemTemplate>
<DataTemplate DataType="local:Person">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Image x:Name="img">
<Image.Style>
<Style TargetType="Image">
<Setter Property="Width" Value="16"/>
<Setter Property="Height" Value="16"/>
<Style.Triggers>
<DataTrigger Binding="{Binding IsSelected,RelativeSource={RelativeSource AncestorType={x:Type ListBoxItem}}}" Value="true">
<Setter Property="Width" Value="24"/>
<Setter Property="Height" Value="24"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Image.Style>
</Image>
<TextBlock Grid.Column="1" Text="{Binding Name}"/>
</Grid>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding IsFemale}" Value="true">
<Setter Property="Source" Value="./image/20140324072056503_easyicon_net_32.png" TargetName="img"/>
</DataTrigger>
<DataTrigger Binding="{Binding IsFemale}" Value="false">
<Setter Property="Source" Value="./image/20140324072142365_easyicon_net_32.png" TargetName="img"/>
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Window>
其中用了RelativeSource來尋找上級ListBoxItem對象來進行綁定達到目的。
代碼
作者:FoolRabbit
出處:http://blog.csdn.net/rabbitsoft_1987
歡迎任何形式的轉載,未經作者同意,請保留此段聲明!