我在listview中有一个扩展器而不是bind。
我还有另一个按钮可以折叠/扩展所有扩展器。
在后面的代码中,我无法使用代码找到扩展器:Expander exp = (Expander)listViewResult.FindResource("MyExpander");
有任何想法吗?
<ListView Name="listViewResult" Margin="0,172,-10,-491" BorderBrush="Gray" BorderThickness="1"
TextElement.FontFamily="Segoe UI" TextElement.FontSize="12"
Background="White"
GridViewColumnHeader.Click="GridViewColumnHeaderClickedHandler" >
<ListView.View>
<GridView ColumnHeaderContainerStyle="{StaticResource GridViewColumnHeaderStyle}" >
……
</GridView>
</ListView.View>
<ListView.GroupStyle>
<GroupStyle>
<GroupStyle.ContainerStyle>
<Style TargetType="{x:Type GroupItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<Expander Name="MyExpander" IsExpanded="False">
<Expander.Header>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Name}" FontWeight="Bold" VerticalAlignment="Bottom" />
</StackPanel>
</Expander.Header>
<ItemsPresenter Margin="20,0,0,0" />
<!--<ItemsPresenter />-->
</Expander>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</GroupStyle.ContainerStyle>
</GroupStyle>
</ListView.GroupStyle>
</ListView>
答案 0 :(得分:2)
使用以下方法查找Visual树中的控件。
public static Visual GetDescendantByName (Visual element, string name)
{
if (element == null) return null;
if (element is FrameworkElement
&& (element as FrameworkElement).Name == name) return element;
Visual result = null;
if (element is FrameworkElement)
(element as FrameworkElement).ApplyTemplate();
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(element); i++)
{
Visual visual = VisualTreeHelper.GetChild(element, i) as Visual;
result = GetDescendantByName(visual, name);
if (result != null)
break;
}
return result;
}
其中element将是您的ListView,name将是您要查找的FrameworkElement的名称。
答案 1 :(得分:1)
为了扩展/折叠所有扩展器,您可以通过查找集合中的所有子项找到所有扩展器
调用方法:
Collection<Expander> collection = FindVisualChild<Expander>(listViewResult);
foreach (Expander expander in collection)
{
expander.IsExpanded = true;
}
方法:
private static Collection<T> FindVisualChild<T>(DependencyObject current) where T : DependencyObject
{
if (current == null)
{
return null;
}
var children = new Collection<T>();
FindVisualChild (current, children);
return children;
}
private static void FindVisualChild<T>(DependencyObject current, Collection<T> children) where T : DependencyObject
{
if (current != null)
{
if (current.GetType() == typeof(T))
{ children.Add((T)current); }
for (int i = 0; i < System.Windows.Media.VisualTreeHelper.GetChildrenCount(current); i++)
{
FindVisualChild (System.Windows.Media.VisualTreeHelper.GetChild(current, i), children);
}
}
}
答案 2 :(得分:0)
尝试使用x:Name属性来定义扩展器的名称,下面的代码可以帮助: Expander exp =(Expander)listViewResult.FindName(“MyExpander”);