Windows8:ListBox与ComboBox
ListBox
对于所有的集合控件,都是一样的使用方法,往里面放东西就两种途径:
1、数据绑定;
2、手动添加项。
而ListBox对应的项是ListBoxItem,说得更明白一些,它就是一个ContentControl,就像Button一样,都有一个Content属性,而我们就通过这个属性来设置项里面要显示的东西。对于数据绑定而言,因为是批量化的,所以,这个时候,就要用上DataTemplate。
ListBox的数据绑定的例子:
<GridBackground="{StaticResource ApplicationPageBackgroundThemeBrush}">
<ListBoxx:Name="list"Width="365"/>
</Grid>
在MainPage类的构造函数中设置数据源,其实就是设置它的ItemsSource属性
public MainPage()
{
this.InitializeComponent();
string[] items = {"赵","钱","孙","李","周","吴","郑","王"};
this.list.ItemsSource = items;
}
ComboBox
其实与ListBox是一样的,只不过它是一个下拉列表框罢了。其项列表对应着是ComboBoxItem类。
考虑下面的例子,我们在ComboBox里面放些东东,然后,当我们选择了特定项后,TextBlock中文本的颜色随之改变。
1 先布局
<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
<StackPanel>
<ComboBox x:Name="cb" Width="275"HorizontalAlignment="Left">
<ComboBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Rectangle Grid.Column="0" Width="25" Height="25"Margin="5" Fill="{Binding Path=Brush}"/>
<TextBlock Grid.Column="1" Text="{Binding Path=ColorName}" VerticalAlignment="Center" Margin="3,2,2,2"/>
</Grid>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
<TextBlock Margin="5,20,0,0" FontSize="60" FontWeight="Black" Text="文本颜色" x:Name="tb"/>
</StackPanel>
</Grid>
在MainPage类的构造函数中,为ComboBox添加4个可选项。并且处理它的SelectionChanged事件,对于绑定,不必定义一个类这么麻烦,别忘了,.net里面有一个很灵活的类型——dynamic,再配全new 关键字,就可以动态定义一个对象出来。
public MainPage()
{
this.InitializeComponent();
List<dynamic> colorList = new List<dynamic>();
colorList.Add(new {
Brush = new SolidColorBrush(Colors.Yellow),
ColorName = "黄色"
});
colorList.Add(new
{
Brush = new SolidColorBrush(Colors.Blue),
ColorName = "蓝色"
});
colorList.Add(new
{
Brush = new SolidColorBrush(Colors.Gray),
ColorName = "灰色"
});
colorList.Add(new
{
Brush = new SolidColorBrush(Colors.Pink),
ColorName = "粉红色"
});
this.cb.ItemsSource = colorList;
// 绑定事件,对ComboBox的选择作出响应
cb.SelectionChanged += (a, args) =>
{
if (args.AddedItems.Count <= 0)
{
return;
}
dynamic item = (dynamic)args.AddedItems[0];
if (item != null)
{
this.tb.Foreground = item.Brush;
}
};
if (cb.Items.Count > 0)
{
cb.SelectedIndex = 0;
}
}