For example, my TreeViewItem' header consists of TextBlock and Image. How I can get references to them?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
I'm not sure if I got you right, but if you want to get visual children of an element, try using VisualTreeHelper.GetChild
and VisualTreeHelper.GetChildrenCount
.
PS: usually it's more problematic to get a reference to the TreeViewItem itself...
UPDATE (A code example for future generations):
private IEnumerable<DependencyObject> GetChildren(DependencyObject parent)
{
var count = VisualTreeHelper.GetChildrenCount(parent);
if (count > 0)
{
for (int i = 0; i < count; i++)
yield return VisualTreeHelper.GetChild(parent, i);
}
else
yield break;
}
private DependencyObject FindInTheVT(DependencyObject parent,Predicate<DependencyObject> predicate)
{
IEnumerable<DependencyObject> layer = GetChildren(parent);
while (layer.Any())
{
foreach (var d in layer)
if (predicate(d)) return d;
layer = layer.SelectMany(x => GetChildren(x));
}
return null;
}
回答2:
If you have something like this (created in Xaml or code):
TreeViewItem Item = new TreeViewItem();
StackPanel HeaderLayout = new StackPanel() { Orientation = Orientation.Horizontal };
HeaderLayout.Children.Add(new Image());
HeaderLayout.Children.Add(new TextBlock() { Text = "tv item" });
Item.Header = HeaderLayout;
you can use something like:
foreach (object Control in ((StackPanel)Item.Header).Children)
{
if (Control is Image)
{
//get the image control: Image img = (Image)Control;
}
else if (Control is TextBlock)
{
//get the textblock: TextBlock tb = (TextBlock)Control;
}
}
I don't recommend doing this. It will be better if you create a custom header instead (a class that contains Image and TextBlock properties) and assign that to your header, or a custom Template.