1.使用ListBox绑定Dictionary字典数据
ListBox常用事件SelectionChanged
private void bindListBox() { Dictionary<string, string> dic = new Dictionary<string, string>(); foreach (var item in Fonts.SystemFontFamilies.OrderBy(q => q.Source)) { dic.Add(item.Source, "---->" + string.Join(",", item.FamilyNames.Select(q => q.ToString()))); //dic.Add(item.Source,"------"); } listBox.ItemsSource = dic; } //选中结果事件 private void listBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { ListBox thisBox = e.Source as ListBox; //e.AddedItems 所有选中的结果 //e.RemovedItems 所有未选中的结果 //解析结果是 Key Value键值对 KeyValuePair<string, string> item = (KeyValuePair<string, string>)e.AddedItems[0]; }
Xaml
<Grid> <Grid.RowDefinitions> <RowDefinition Height="57*"/> <RowDefinition Height="347*"/> </Grid.RowDefinitions> <ListBox x:Name="listBox" Grid.Row="1" SelectionChanged="listBox_SelectionChanged" /> <Label x:Name="label" Content="系统字体显示" FontWeight="Bold" Foreground="Red" HorizontalAlignment="Left" Margin="36,22,0,0" VerticalAlignment="Top" Height="26" Width="97"/> </Grid>
2.使用字典集合单项绑定,ListBox.ItemTemplete模板
后台同上
Xaml定义:
<Grid> <Grid.RowDefinitions> <RowDefinition Height="21*"/> <RowDefinition Height="248*"/> </Grid.RowDefinitions> <ListBox x:Name="listBox" Grid.Row="1"> <ListBox.ItemTemplate> <DataTemplate> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="100"></ColumnDefinition> <ColumnDefinition Width="*"></ColumnDefinition> </Grid.ColumnDefinitions> <Label Grid.Column="0" Background="LightBlue" Content="{Binding Path=Key,Mode=OneWay}"/> <TextBox Grid.Column="1" Text="{Binding Path=Value,Mode=OneWay}"/> </Grid> </DataTemplate> </ListBox.ItemTemplate> </ListBox> </Grid>