wpf 遍历listbox的Item
程序员文章站
2022-04-05 15:22:16
...
<StackPanel>
<ListBox Width="400"
Height="300" x:Name="describeString" ItemTemplate="{DynamicResource ListBoxTemplate}" />
</StackPanel>
<DataTemplate x:Key="ListBoxTemplate">
<Grid MinWidth="79">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="5"></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
</Grid.ColumnDefinitions>
<TextBlock
Grid.Column="1"
Text="{Binding SampleName}"
TextWrapping="Wrap"
MouseDown="TextBlock_MouseDown"
HorizontalAlignment="Center"
VerticalAlignment="Center"
/>
</Grid>
</DataTemplate>
List blocks = FindFirstVisualChild(this.describeString);
//遍历指定容器,根据控件名,返回适配的控件集合
public List<T> FindFirstVisualChild<T>(DependencyObject obj) where T : DependencyObject
{
List<T> childList = new List<T>();
//遍历指定容器
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
{
DependencyObject child = VisualTreeHelper.GetChild(obj, i);
if (child != null && child is T)
{
childList.Add((T)child);
}
//如果不存在,则继续遍历指定容器的子容器(则如果指定容器的子容器也就是第二层,遍历存在匹配的控件则跳出。不再遍历其第三层,继续遍历第二层)
else
{
List<T> t2 = FindFirstVisualChild<T>(child);
if (t2 != null && t2.Count > 0)
{
foreach (T t in t2)
{
childList.Add(t);
}
}
}
}
return childList;
}
根据名称查找
//遍历指定容器,根据控件名,返回适配的控件集合
public List<T> FindFirstVisualChild<T>(DependencyObject obj, string childName) where T : DependencyObject
{
List<T> childList = new List<T>();
//遍历指定容器
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)
{
childList.Add((T)child);
}
//如果不存在,则继续遍历指定容器的子容器(则如果指定容器的子容器也就是第二层,遍历存在匹配的控件则跳出。不再遍历其第三层,继续遍历第二层)
else
{
List<T> t2 = FindFirstVisualChild<T>(child, childName);
if (t2 != null && t2.Count > 0)
{
foreach (T t in t2)
{
childList.Add(t);
}
}
}
}
return childList;
}
上一篇: PHP 金额数字转换成英文
下一篇: 较酷的表单验证(jQuery+css3)