我有一个多选择列表框,其中用户可以勾选列表中的多个项目。 目前,我有这么当复选框被选中的一个ListBoxItem它内还被选中:
private void CheckBox_Checked(object sender, RoutedEventArgs e)
{
//Select the Item using the DataContext of the Button
object clicked = (e.OriginalSource as FrameworkElement).DataContext;
var lbi = LstDistro.ItemContainerGenerator.ContainerFromItem(clicked) as ListBoxItem;
lbi.IsSelected = true;
}
现在我试图做到这一点的其他方式。 只要选择了一个ListBoxItem中的复选框被选中。 到目前为止,我有,所以你选择的第一个项目将获得打勾但是,没有任何其他项目后,选择得到打勾。 我需要以某种方式把它遍历所有当前选定的项目。
我当前的代码:
WPF:
<ListBox x:Name="LstDistro" HorizontalAlignment="Left" Margin="10,10,0,42" Width="235" BorderBrush="Black" BorderThickness="2,2,1,1" SelectionMode="Multiple" SelectionChanged="LstDistro_SelectionChanged">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Canvas x:Name="EventItem" HorizontalAlignment="Left" Height="42" VerticalAlignment="Top" Width="215" Background="{Binding Path=LBackground}">
<Label Content="{Binding LInits}" HorizontalAlignment="Left" Height="33" VerticalAlignment="Top" Width="40" FontWeight="Bold" FontSize="12" Canvas.Top="5"/>
<Label Content="{Binding LFullName}" HorizontalAlignment="Left" Height="33" VerticalAlignment="Top" Width="164" FontSize="12" Canvas.Left="40" Canvas.Top="5"/>
<CheckBox x:Name="ChkName" Height="20" Width="20" Canvas.Left="190" Canvas.Top="12" Checked="CheckBox_Checked" IsChecked="False"/>
</Canvas>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
C#:
private void CheckBox_Checked(object sender, RoutedEventArgs e)
{
//Select the Item using the DataContext of the Button
object clicked = (e.OriginalSource as FrameworkElement).DataContext;
var lbi = LstDistro.ItemContainerGenerator.ContainerFromItem(clicked) as ListBoxItem;
lbi.IsSelected = true;
}
private void LstDistro_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
//Get the current selected item
ListBoxItem item = LstDistro.ItemContainerGenerator.ContainerFromIndex(LstDistro.SelectedIndex) as ListBoxItem;
CheckBox ChkName = null;
//Get the item's template parent
ContentPresenter templateParent = GetFrameworkElementByName<ContentPresenter>(item);
//Get the DataTemplate that the Checkbox is in.
DataTemplate dataTemplate = LstDistro.ItemTemplate;
ChkName = dataTemplate.FindName("ChkName", templateParent) as CheckBox;
ChkName.IsChecked = true;
}
private static T GetFrameworkElementByName<T>(FrameworkElement referenceElement) where T : FrameworkElement
{
FrameworkElement child = null;
for (Int32 i = 0; i < VisualTreeHelper.GetChildrenCount(referenceElement); i++)
{
child = VisualTreeHelper.GetChild(referenceElement, i) as FrameworkElement;
System.Diagnostics.Debug.WriteLine(child);
if (child != null && child.GetType() == typeof(T))
{ break; }
else if (child != null)
{
child = GetFrameworkElementByName<T>(child);
if (child != null && child.GetType() == typeof(T))
{
break;
}
}
}
return child as T;
}