×
Namespaces

Variants
Actions
Revision as of 08:36, 30 November 2012 by hamishwillee (Talk | contribs)

在WP中实现一个横向的ListBox

From Nokia Developer Wiki
Jump to: navigation, search
WP Metro Icon UI.png
SignpostIcon XAML 40.png
SignpostIcon WP7 70px.png
Article Metadata

代码示例
兼容于
文章
renlin 在 26 Oct 2012 创建
最后由 hamishwillee 在 30 Nov 2012 编辑

实现

本文利用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就实现了。效果如图所示:
HorizontalListBox.png
代码示例:Media:HengListbox.zip

相关链接

169 page views in the last 30 days.
×