您必須爲您的DragDropItemsControl
創建您自己的AutomationPeer
,併爲您的自定義控件項目,然後您將能夠將AutomationId定義爲您的項目對象的標識符。
public class DragDropItemsControl : ItemsControl
{
protected override AutomationPeer OnCreateAutomationPeer()
{
return new DragDropItemsAutomationPeer(this);
}
}
自定義AutomationPeer
類爲您的控件。
public class DragDropItemsControlAutomationPeer : ItemsControlAutomationPeer
{
public DragDropItemsControlAutomationPeer(DragDropItemsControl owner)
: base(owner)
{
}
protected override string GetClassNameCore()
{
return "DragDropItemsControl";
}
protected override ItemAutomationPeer CreateItemAutomationPeer(object item)
{
return new DragDropItemsControlItemAutomationPeer(item, this);
}
}
定製AutomationPeer
類爲您的控制項目。 這裏的重要部分是方法GetAutomationIdCore()
的實施。
public class DragDropItemsControlItemAutomationPeer : ItemAutomationPeer
{
public DragDropItemsControlItemAutomationPeer(object item, ItemsControlAutomationPeer itemsControlAutomationPeer)
: base(item, itemsControlAutomationPeer)
{
}
protected override string GetClassNameCore()
{
return "DragDropItemsControl_Item";
}
protected override string GetAutomationIdCore()
{
return (base.Item as MyTestItemObject)?.ItemId;
}
protected override AutomationControlType GetAutomationControlTypeCore()
{
return base.GetAutomationControlType();
}
}
對於下面的XAML代碼
<local:MyItemsControl x:Name="icTodoList" AutomationProperties.AutomationId="TestItemsControl">
<local:MyItemsControl.ItemTemplate>
<DataTemplate>
<Border >
<TextBlock Cursor="Hand" Text="{Binding Title}" />
</Border>
</DataTemplate>
</local:MyItemsControl.ItemTemplate>
</local:MyItemsControl>
初始化代碼後面
public MyMainWindow()
{
InitializeComponent();
List<MyTestItemObject> items = new List<MyTestItemObject>();
items.Add(new MyTestItemObject() { Title = "Learning TestStack.White", ItemId="007" });
items.Add(new MyTestItemObject() { Title = "Improve my english", ItemId = "008" });
items.Add(new MyTestItemObject() { Title = "Work it out", ItemId = "009" });
icTodoList.ItemsSource = items;
}
public class MyTestItemObject
{
public string Title { get; set; }
public string ItemId { get; set; }
}
我們可以看到UIAVerify
![UIAVerify screen](https://i.stack.imgur.com/PUe9f.jpg)
樣品檢查值的代碼
// retrieve the custom control
IUIItem theItemsControl = window.Get(SearchCriteria.ByAutomationId("008"));
if (theItemsControl is CustomUIItem)
{
// retrieve the custom control container
IUIItemContainer controlContainer = (theItemsControl as CustomUIItem).AsContainer();
// get the child components
WPFLabel theTextBlock = controlContainer.Get<WPFLabel>(SearchCriteria.Indexed(0));
// get the text value
string textValue = theTextBlock.Text;
}
你問你如何給集合中的每個項目個別Name/AutomationId? – LordWilmore
@LordWilmore是的。我沒有找到任何解決方案從ItemsControl –
獲取每個項目。因此,您需要將automationproperties.automationid設置爲獨特的東西。因此,選擇一個合適的字符串,並添加一個前綴,該前綴綁定到對象內唯一的內容,例如一個ID。 – LordWilmore