У меня возникают трудности с доступом к элементам управления, которые находятся в каждом узле TreeView. Я могу получить доступ к узлам дерева просмотра, но не к элементам управления в них (кнопка расширителя и ее сообщения). TreeView привязан к массиву ValidationResult (код ниже).Как получить доступ к элементам связанного с данными WPF TreeView из кодированных пользовательских интерфейсов
Я загрузил изображение элемента управления здесь: http://s30.postimg.org/j2vszwc01/Results_form.jpg Отличительная черта границы - от создателя кодированного пользовательского интерфейса. Он не видит ничего, что ниже уровня узла TreeViewItem.
Контроль просмотра результатов определяется следующим образом:
<UserControl x:Class="ResultsForm.ValidationResultsViewerUI"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:ResultsForm"
mc:Ignorable="d"
d:DesignHeight="400" d:DesignWidth="400">
<UserControl.Resources>
<local:TreeViewDimensionConvertor x:Key="treeViewWidthConvertor"/>
<DataTemplate x:Key="errorTemplate">
<Grid Name="resultsGrid" Width="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type TreeView}}, Path=ActualWidth, Converter={StaticResource treeViewWidthConvertor}}">
<Grid.Resources>
<Style TargetType="Border" x:Key="errorBorderStyle" >
<Style.Resources>
<LinearGradientBrush x:Key="errorBackBrush" StartPoint="0.5,0" EndPoint="0.5,1">
<GradientStop Color="#EF3132" Offset="0.1" />
<GradientStop Color="#D62B2B" Offset="0.9" />
</LinearGradientBrush>
</Style.Resources>
<Setter Property="Background" Value="{StaticResource errorBackBrush}"/>
</Style>
</Grid.Resources>
<Expander Name="expanderTest">
<Expander.Header>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="300*"/>
<ColumnDefinition Width="5"/>
<ColumnDefinition Width="50*"/>
</Grid.ColumnDefinitions>
<Border Style="{StaticResource errorBorderStyle}" Grid.Column="0">
<TextBlock Text="{Binding Message}"
FontSize="12"
TextWrapping="Wrap"
Foreground="White">
</TextBlock>
</Border>
<TextBlock Grid.Column="2" HorizontalAlignment="Left">
<Hyperlink Tag="{Binding UrlSuffix}">Details</Hyperlink>
</TextBlock>
</Grid>
</Expander.Header>
<TextBox Text="{Binding Description}"
AcceptsReturn="True"
IsReadOnly="True"
TextWrapping="Wrap"
Width="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type TreeView}}, Path=ActualWidth, Converter={StaticResource treeViewWidthConvertor}}">
</TextBox>
</Expander>
</Grid>
</DataTemplate>
<DataTemplate x:Key="warningTemplate">
<Grid Width="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type TreeView}}, Path=ActualWidth, Converter={StaticResource treeViewWidthConvertor}}">
<Grid.Resources>
<Style TargetType="Border" x:Key="warningBorderStyle" >
<Style.Resources>
<LinearGradientBrush x:Key="warningBackBrush" StartPoint="0.5,0" EndPoint="0.5,1">
<GradientStop Color="#FFFDE203" Offset="0.1" />
<GradientStop Color="#FFFDDC00" Offset="0.9" />
</LinearGradientBrush>
</Style.Resources>
<Setter Property="Background" Value="{StaticResource warningBackBrush}"/>
</Style>
</Grid.Resources>
<Expander Grid.Column="0" Grid.Row="1" Grid.ColumnSpan="2">
<Expander.Header>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="300*"/>
<ColumnDefinition Width="5"/>
<ColumnDefinition Width="50*"/>
</Grid.ColumnDefinitions>
<Border Grid.Column="0" Style="{StaticResource warningBorderStyle}">
<TextBlock Text="{Binding Message}" FontSize="12" TextWrapping="Wrap" Foreground="Black" />
</Border>
<TextBlock Grid.Column="2" HorizontalAlignment="Left">
<Hyperlink Tag="{Binding UrlSuffix}">Details</Hyperlink>
</TextBlock>
</Grid>
</Expander.Header>
<TextBox Text="{Binding Description}"
AcceptsReturn="True"
IsReadOnly="True"
TextWrapping="Wrap"
Width="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type TreeView}}, Path=ActualWidth, Converter={StaticResource treeViewWidthConvertor}}" />
</Expander>
</Grid>
</DataTemplate>
<local:TemplateSelector x:Key="warningOrErrorTemplateSelector"
ErrorTemplate="{StaticResource errorTemplate}"
WarningTemplate="{StaticResource warningTemplate}"/>
<DataTemplate x:Key="childTemplate">
<TreeViewItem Header="child"
ItemTemplateSelector="{StaticResource warningOrErrorTemplateSelector}"
IsExpanded="True"
Focusable="False"
IsSelected="False">
<TreeViewItem.Resources>
<CollectionViewSource x:Key="childErrors" Source="{Binding Errors}"/>
<CollectionViewSource x:Key="childWarnings" Source="{Binding Warnings}"/>
</TreeViewItem.Resources>
<TreeViewItem.ItemsSource>
<CompositeCollection>
<CollectionContainer Collection="{Binding Source={StaticResource childErrors}}"/>
<CollectionContainer Collection="{Binding Source={StaticResource childWarnings}}"/>
</CompositeCollection>
</TreeViewItem.ItemsSource>
</TreeViewItem>
</DataTemplate>
<local:TemplateSelector x:Key="templateSelector"
ErrorTemplate="{StaticResource errorTemplate}"
WarningTemplate="{StaticResource warningTemplate}"
VerificationResultTemplate="{StaticResource childTemplate}"/>
<DataTemplate x:Key="parentTemplate">
<TreeViewItem Header="{Binding Description}"
ItemTemplateSelector="{StaticResource templateSelector}"
IsExpanded="True"
Focusable="False"
IsSelected="False">
<TreeViewItem.Resources>
<CollectionViewSource x:Key="errors" Source="{Binding Errors}"/>
<CollectionViewSource x:Key="warnings" Source="{Binding Warnings}"/>
<CollectionViewSource x:Key="children" Source="{Binding ChildrenResults}"/>
</TreeViewItem.Resources>
<TreeViewItem.ItemsSource>
<CompositeCollection>
<CollectionContainer Collection="{Binding Source={StaticResource errors}}"/>
<CollectionContainer Collection="{Binding Source={StaticResource warnings}}"/>
<CollectionContainer Collection="{Binding Source={StaticResource children}}"/>
</CompositeCollection>
</TreeViewItem.ItemsSource>
</TreeViewItem>
</DataTemplate>
</UserControl.Resources>
<Grid>
<Border>
<TreeView Name="resultTree" ItemTemplate="{StaticResource parentTemplate}" Focusable="False" ItemsSource="{Binding}">
<TreeView.Resources>
<SolidColorBrush Color="White" x:Key="{x:Static SystemColors.HighlightBrushKey}"/>
</TreeView.Resources>
</TreeView>
</Border>
</Grid>
</UserControl>
Проверка класс результат определяется как этот (VerificationError и VerificationWarning каждая содержит описание и сообщение строковые поля):
[DataContract]
public class ValidationResult
{
[DataMember(Order = 1)]
public VerificationError[] Errors { get; set; }
[DataMember(Order = 2)]
public VerificationWarning[] Warnings { get; set; }
[DataMember(Order = 3)]
public virtual string Description { get; set; }
}
Что мне нужно сделать для доступа к сообщениям в TreeView?
Редактировать: Я попытался получить доступ к элементам программно и установил AutomationId каждого TreeViewItem, но ни один из них не работал. Я также создал аналогичную иерархию без привязки данных к древовидному представлению, и у меня не было никаких проблем с доступом к элементам управления. Я предполагаю, что проблема связана с привязкой данных (http://blogs.msdn.com/b/tapas_sahoos_blog/archive/2011/12/13/verifying-wpf-data-bound-item-controls-in-coded-ui-test-recording-context.aspx), но я не знаю, как ее исправить.
Спасибо за ваш ответ! Да, я пробовал это, результат немного смешной. Дети TreeViewItem - кнопка со стрелкой TreeViewItem (а не кнопка расширения круга) и элемент ValidationResult (который, как я предполагаю, сам является узлом ...). И внутри контроля ValidationResult те же два элемента и так далее ... – Mike