CacheRequest.Activate Метод
Определение
Важно!
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
Определяет данный запрос CacheRequest как активную спецификацию для элементов, которые возвращаются, когда элемент AutomationElement запрашивается в том же потоке.
public:
IDisposable ^ Activate();
public IDisposable Activate ();
member this.Activate : unit -> IDisposable
Public Function Activate () As IDisposable
Возвращаемое значение
Объект, который может использоваться для удаления запроса CacheRequest.
Примеры
В следующем примере показано, как использовать Activate для кэширования шаблонов и свойств.
/// <summary>
/// Caches and retrieves properties for a list item by using CacheRequest.Activate.
/// </summary>
/// <param name="elementList">Element from which to retrieve a child element.</param>
/// <remarks>
/// This code demonstrates various aspects of caching. It is not intended to be
/// an example of a useful method.
/// </remarks>
private void CachePropertiesByActivate(AutomationElement elementList)
{
AutomationElement elementListItem;
// Set up the request.
CacheRequest cacheRequest = new CacheRequest();
cacheRequest.Add(AutomationElement.NameProperty);
cacheRequest.Add(AutomationElement.IsEnabledProperty);
cacheRequest.Add(SelectionItemPattern.Pattern);
cacheRequest.Add(SelectionItemPattern.SelectionContainerProperty);
// Obtain an element and cache the requested items.
using (cacheRequest.Activate())
{
Condition cond = new PropertyCondition(AutomationElement.IsSelectionItemPatternAvailableProperty, true);
elementListItem = elementList.FindFirst(TreeScope.Children, cond);
}
// The CacheRequest is now inactive.
// Retrieve the cached property and pattern.
SelectionItemPattern pattern;
String itemName;
try
{
itemName = elementListItem.Cached.Name;
pattern = elementListItem.GetCachedPattern(SelectionItemPattern.Pattern) as SelectionItemPattern;
}
catch (InvalidOperationException)
{
Console.WriteLine("Object was not in cache.");
return;
}
// Alternatively, you can use TryGetCachedPattern to retrieve the cached pattern.
object cachedPattern;
if (true == elementListItem.TryGetCachedPattern(SelectionItemPattern.Pattern, out cachedPattern))
{
pattern = cachedPattern as SelectionItemPattern;
}
// Specified pattern properties are also in the cache.
AutomationElement parentList = pattern.Cached.SelectionContainer;
// The following line will raise an exception, because the HelpText property was not cached.
/*** String itemHelp = elementListItem.Cached.HelpText; ***/
// Similarly, pattern properties that were not specified in the CacheRequest cannot be
// retrieved from the cache. This would raise an exception.
/*** bool selected = pattern.Cached.IsSelected; ***/
// This is still a valid call, even though the property is in the cache.
// Of course, the cached value and the current value are not guaranteed to be the same.
itemName = elementListItem.Current.Name;
}
''' <summary>
''' Caches and retrieves properties for a list item by using CacheRequest.Activate.
''' </summary>
''' <param name="elementList">Element from which to retrieve a child element.</param>
''' <remarks>
''' This code demonstrates various aspects of caching. It is not intended to be
''' an example of a useful method.
''' </remarks>
Private Sub CachePropertiesByActivate(ByVal elementList As AutomationElement)
' Set up the request.
Dim myCacheRequest As New CacheRequest()
myCacheRequest.Add(AutomationElement.NameProperty)
myCacheRequest.Add(AutomationElement.IsEnabledProperty)
myCacheRequest.Add(SelectionItemPattern.Pattern)
myCacheRequest.Add(SelectionItemPattern.SelectionContainerProperty)
Dim elementListItem As AutomationElement
' Obtain an element and cache the requested items.
Using myCacheRequest.Activate()
Dim myCondition As New PropertyCondition( _
AutomationElement.IsSelectionItemPatternAvailableProperty, True)
elementListItem = elementList.FindFirst(TreeScope.Children, myCondition)
End Using
' The CacheRequest is now inactive.
' Retrieve the cached property and pattern.
Dim pattern As SelectionItemPattern
Dim itemName As String
Try
itemName = elementListItem.Cached.Name
pattern = DirectCast(elementListItem.GetCachedPattern(SelectionItemPattern.Pattern), _
SelectionItemPattern)
Catch ex As InvalidOperationException
Console.WriteLine("Object was not in cache.")
Return
End Try
' Alternatively, you can use TryGetCachedPattern to retrieve the cached pattern.
Dim cachedPattern As Object = Nothing
If True = elementListItem.TryGetCachedPattern(SelectionItemPattern.Pattern, cachedPattern) Then
pattern = DirectCast(cachedPattern, SelectionItemPattern)
End If
' Specified pattern properties are also in the cache.
Dim parentList As AutomationElement = pattern.Cached.SelectionContainer
' The following line will raise an exception, because the HelpText property was not cached.
'** String itemHelp = elementListItem.Cached.HelpText; **
' Similarly, pattern properties that were not specified in the CacheRequest cannot be
' retrieved from the cache. This would raise an exception.
'** bool selected = pattern.Cached.IsSelected; **
' This is still a valid call, even though the property is in the cache.
' Of course, the cached value and the current value are not guaranteed to be the same.
itemName = elementListItem.Current.Name
End Sub
Комментарии
Использование этого метода обычно предпочтительнее использования Push и Pop в качестве средства активации CacheRequest. Объект помещается в стек при Activate вызове, а затем выскочил при удалении. Чтобы обеспечить удаление, поместите возвращаемое значение в using
блок (Using
в Visual Basic).