我在silverlight app中使用手风琴。在accordionItem我有一个列表框,我需要访问扩展的手风琴项目和手风琴的这个列表框。
我很难找到手风琴和它所持有的列表框。我该怎么做呢?
我试图解决的是使用以下扩展类:
public static IEnumerable<DependencyObject> GetVisuals(this DependencyObject root)
{
int count = VisualTreeHelper.GetChildrenCount(root);
for (int i = 0; i < count; i++)
{
var child = VisualTreeHelper.GetChild(root, i);
yield return child;
foreach (var descendants in child.GetVisuals())
{
yield return descendants;
}
}
}
然后把它叫作我的手风琴:
foreach (var control in MyAccordion.GetVisuals().OfType<ListBox>())
{
// Do something with the listbox
}
不幸的是,即使没有OfType扩展方法,当在扩展方法中调用GetChildrenCount时,Accordion报告为0。
更新
我找到了一种使用以下代码访问AccordionItem的方法
int selectedIndex = OrganiChartAccordion.SelectedIndex;
AccordionItem accordionItem = OrganiChartAccordion.ItemContainerGenerator.ContainerFromIndex(selectedIndex) as AccordionItem;
在AccordionItem中,我使用DataTemplate来渲染数据。在DataTemplate中,我有两个列表框。我需要访问所选择的accordionitem中的数据模板,并在datatemplate中访问两个列表框。
答案 0 :(得分:2)
试试这个:
<UserControl x:Class="SilverlightApplication10.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:layout="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Layout.Toolkit"
mc:Ignorable="d"
d:DesignHeight="300"
d:DesignWidth="400">
<Grid x:Name="LayoutRoot"
Background="White">
<layout:Accordion x:Name="Accordion1">
<layout:Accordion.Items>
<layout:AccordionItem Header="Header 1">
<ListBox>
<ListBox.Items>
<ListBoxItem Content="Item 1"></ListBoxItem>
<ListBoxItem Content="Item 2"></ListBoxItem>
<ListBoxItem Content="Item 3"></ListBoxItem>
</ListBox.Items>
</ListBox>
</layout:AccordionItem>
<layout:AccordionItem Header="Header 2">
<ListBox>
<ListBox.Items>
<ListBoxItem Content="Item 1"></ListBoxItem>
<ListBoxItem Content="Item 2"></ListBoxItem>
<ListBoxItem Content="Item 3"></ListBoxItem>
</ListBox.Items>
</ListBox>
</layout:AccordionItem>
</layout:Accordion.Items>
</layout:Accordion>
</Grid>
</UserControl>
代码隐藏:
using System;
using System.Diagnostics;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
namespace SilverlightApplication10
{
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
this.Loaded += MainPage_Loaded;
}
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
Accordion1.Items.ToList().ForEach(item =>
{
((item as AccordionItem).Content as ListBox).Items.ToList().ForEach(listBoxItem =>
{
var content = ((ListBoxItem)listBoxItem).Content;
Debug.WriteLine(content);
});
});
}
}
}