方法
public List<T> GetChildObjects<T>(DependencyObject obj, string name) where T : FrameworkElement
{
DependencyObject child = null;
List<T> childList = new List<T>();
for (int i = 0; i <= VisualTreeHelper.GetChildrenCount(obj) - 1; i++)
{
child = VisualTreeHelper.GetChild(obj, i);
if (child is T && (((T)child).Name == name || string.IsNullOrEmpty(name)))
{
childList.Add((T)child);
}
childList.AddRange(GetChildObjects<T>(child, ""));//指定集合的元素添加到List队尾
}
return childList;
}
private void cbName1_Click(object sender, RoutedEventArgs e)
{
this.sp1.Visibility = Visibility.Visible;
string contentname = ((CheckBox)sender).Content.ToString();
List<CheckBox> collection = GetChildObjects<CheckBox>(lbJuDingZeRen, "");
foreach (CheckBox item in collection)
{
if (item.Content.ToString() == contentname)
{
item.IsChecked = true;
}
else
{
item.IsChecked = false;
}
}
}
前台
<DataTemplate x:Key="DataTemplateListBox1">
<Grid>
<CheckBox x:Name="cbName1" Content="{Binding 局定责任}" Checked="cbName1_Click" Unchecked="cbName1_Unchecked" HorizontalAlignment="Right" Margin="0"/>
</Grid>
</DataTemplate>
<ListBox x:Name="lbJuDingZeRen" ItemsSource="{Binding }" ScrollViewer.VerticalScrollBarVisibility="Auto" ItemTemplate="{StaticResource DataTemplateListBox1}"/>