在WP中实现一个横向的ListBox
文章信息
实现
本文利用VirtualizingStackPanel的水平视图的属性来实现一个横向的ListBox. 在项目中的Mainpage.xaml页面中添加ListBox项并设置ListBox.ItemPanel相关属性:
<ListBox Name="TheList" >
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<VirtualizingStackPanel Orientation="Horizontal" CanHorizontallyScroll="True"
HorizontalAlignment="Center"/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
</ListBox>
在MainPage.xaml.cs文件中添加List的数据,这里使用了简单的List<string>作为数据源。
List<string> notes = new List<string>();
notes.Add("Monday");
notes.Add("Tuesday");
notes.Add("Wednesday");
notes.Add("Thursday");
notes.Add("Friday");
notes.Add("Saturday");
notes.Add("Sunday");
TheList.ItemsSource = notes;
这时的ListBox变为横向,但是缺少横向滑动的功能,修改ListBox的默认属性ScrollViewer.HorizontalScrollBarVisibility为Auto和ScrollViewer.VerticalScrollBarVisibility为Disable就可启动横向滑动的功能。然后为ListBoxItem实现一个模板,让其具有一些更直观的用户体验,比如点击某项时字体变大,颜色改变等:
<Style x:Key="MyTextBlockStyle" TargetType="ListBoxItem" >
<Setter Property="FontFamily" Value="Times New Roman"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
<Border Background="Transparent" Width="160">
<VisualStateManager.VisualStateGroups >
<VisualStateGroup x:Name="FocusStates">
<VisualState x:Name="Unfocused">
<Storyboard>
<DoubleAnimation Duration="0" To="21.333" Storyboard.TargetProperty="(Control.FontSize)"
Storyboard.TargetName="textBlock" d:IsOptimized="True"/>
<ColorAnimation Duration="0" To="#FF0E0404" Storyboard.TargetProperty="(Control.Foreground).(SolidColorBrush.Color)" Storyboard.TargetName="textBlock" d:IsOptimized="True"/>
</Storyboard>
</VisualState>
<VisualState x:Name="Focused">
<Storyboard>
<DoubleAnimation Duration="0" To="48" Storyboard.TargetProperty="(Control.FontSize)"
Storyboard.TargetName="textBlock" d:IsOptimized="True"/>
<ColorAnimation Duration="0" To="#FFB53C3C" Storyboard.TargetProperty="(Control.Foreground).(SolidColorBrush.Color)" Storyboard.TargetName="textBlock" d:IsOptimized="True"/>
</Storyboard>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<Grid>
<ContentControl x:Name="textBlock" Content="{Binding}" Background="Black" />
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
到这里一个简单的横向ListBox就实现了。效果如图所示:

代码示例:Media:HengListbox.zip


(no comments yet)