1、ListBox的单选和多选
默认情况下只支持单选
通过设定其SelectionMode可以支持多选
SelectionMode - 选择模式 [System.Windows.Controls.SelectionMode 枚举]
Single - 只允许单选
Multiple - 可以多选(不需要任何辅助键)
Extended - 可以多选(需要 Ctrl 或 Shift 的配合)
2、数据模板和数据绑定
<ListBox x:Name="lbPerson" ItemsSource="{Binding}" SelectionMode="Multiple" Height="118" Margin="53,55,8,0" VerticalAlignment="Top" ScrollViewer.HorizontalScrollBarVisibility="Hidden" SelectionChanged="lbPerson_SelectionChanged">
<ListBox.BorderBrush>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="#FFA3AEB9" Offset="0.058"/>
<GradientStop Color="#FF617584" Offset="1"/>
</LinearGradientBrush>
</ListBox.BorderBrush>
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock x:Name="content" FontWeight="Bold" Foreground="#0b333c" FontSize="14" TextWrapping="Wrap" Text="{Binding CNAME}" Width="50" Height="20"/>
<TextBlock x:Name="content2" FontWeight="Bold" Foreground="#0b333c" FontSize="14" TextWrapping="Wrap" Text="{Binding CMCODE}" Width="100" Height="20"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
/// <summary>
/// 从WebService获取数据,绑定到ListBox的DataContext上
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void cbCounty_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
{
MapClient.ServiceReference1.Region ws = (sender as ComboBox).SelectedItem as MapClient.ServiceReference1.Region;
getMapDataSoapClient client = new getMapDataSoapClient();
client.getRYByADDVCDCompleted += new EventHandler<getRYByADDVCDCompletedEventArgs>(client_getRYByADDVCDCompleted);
client.getRYByADDVCDAsync(ws.RegionCode);
}
void client_getRYByADDVCDCompleted(object sender, getRYByADDVCDCompletedEventArgs e)
{
ObservableCollection<FXJGRY> lists = e.Result;
this.lbPerson.DataContext = lists;
}
public T FindFirstVisualChild<T>(DependencyObject obj, string childName) where T : DependencyObject
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
{
DependencyObject child = VisualTreeHelper.GetChild(obj, i);
if (child != null && child is T && child.GetValue(NameProperty).ToString() == childName)
{
return (T)child;
}
else
{
T childOfChild = FindFirstVisualChild<T>(child, childName);
if (childOfChild != null)
{
return childOfChild;
}
}
}
return null;
}
Dictionary<string, string> dic = new Dictionary<string, string>();
private void lbPerson_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
{
ListBoxItem _selectedItem = (ListBoxItem)(lbPerson.ItemContainerGenerator.ContainerFromItem(this.lbPerson.SelectedItem));
TextBlock myTxt = FindFirstVisualChild<TextBlock>(_selectedItem, "content2");
if (!dic.ContainsValue(myTxt.Text.ToString().Trim()))
{
dic.Add(myTxt.Text.Trim(),myTxt.Text.Trim());
}
foreach (KeyValuePair<string, string> kvp in dic)
{
MessageBox.Show(kvp.Value.ToString());
}
}
3、效果如图