Qt和WP7的Selection List
文章信息
本文展示了如何在Qt和WP7中使用Selection List。
Contents |
简介
使用Selection List,用户可以从一组项目中选择一项或多项。如果有需要,你也可以滚动列表,并且让选中的项高亮显示。 本文在Qt和WP中创建Selection List,列表中包含一年四季。 Qt版使用SelectionListItem以及Selection Dialog,当某个季节被选中后,dialog将关闭, SelectionListItem的副标题会变成选中的季节。 Windows Phone版本使用Silverlight for Windows Phone Toolkit中的ListPicker控件。当某一向被选中后,它会在一个TextBox中显示。
| Qt | Windows Phone |
|---|---|
| Example of Qt | Example of WP |
实现
下面的代码从空项目开始。
Qt项目(main.qml)
我们用SelectionListItem获得选中的项。当用户点击SelectionListItem时,将SelectionDialog打开以显示列表。
SelectionListItem {
id: item
y:51
title: "Select Season"
subTitle: selectionDialog.selectedIndex >= 0
? selectionDialog.model.get(selectionDialog.selectedIndex).name
: "Please select"
onClicked: selectionDialog.open()
SelectionDialog {
id: selectionDialog
titleText: "Select one of the values"
selectedIndex: -1
model: ListModel {
ListElement { name: "Spring" }
ListElement { name: "Summer" }
ListElement { name: "Fall" }
ListElement { name: "Winter" }
}
}
}
当用户选择某一项时,SelectionListItem的副标题会显示它的内容。
WP7项目(MainPage.xaml)
- 首相添加引用至Microsoft.Phone.Controls.Toolkit。
- 在XAML中引用命名空间:
xmlns:toolkit="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit"
xmlns:controls="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls"
xmlns:local="clr-namespace:SelectionListWp7"
添加资源
<phone:PhoneApplicationPage.Resources>
<local:Model x:Key="Model"/>
<DataTemplate x:Key="SeasonsTemplate">
<StackPanel Orientation="Horizontal">
<Ellipse
Fill="{Binding}"
Width="20"
Height="20"
Margin="0 0 6 0"/>
<TextBlock Text="{Binding}"/>
</StackPanel>
</DataTemplate>
</phone:PhoneApplicationPage.Resources>
- 然后使用ListPicker创建列表
<StackPanel>
<toolkit:ListPicker
x:Name="SeasonsSelector"
Header="Season"
ItemsSource="{Binding Seasons}"
SelectedIndex="1"
SelectionChanged="SeasonsSelectionChanged"/>
<TextBlock
x:Name="SeasonsSelection"
Margin="{StaticResource PhoneMargin}"
CacheMode="BitmapCache"/>
</StackPanel>
默认第一项被选中了。
WP7项目(MainPage.xaml.cs)
当用户选择某项时,SeasonsSelectionChanged事件会触发,在事件处理程序中我们将选中的项显示出来。
private void SeasonsSelectionChanged(object sender, SelectionChangedEventArgs e)
{
SeasonsSelection.Text = "Current selection: " + ((0 < e.AddedItems.Count) ? e.AddedItems[0] : "[nothing]");
}
总结
使用SelectionListItem可以创建一个列表。但在WP7中,ListPicker 控件一次最多只能显示5项内容,如果列表太长,会弹出一个全屏的popup显示所有内容。WP7 Toolkit's中的ListPicker控件就是这样设计的,根据列表中的项目数量,自动选择合适的显示方式。
源代码
你可以从这里找到Qt版本的完整源代码:File:SelectionListQt.zip 你可以从这里找到WP7版本的完整源代码:File:SelectionListWP7.zip


(no comments yet)