为了记录我的WPF表单中的用户操作,我添加了一些全局事件处理程序。
我想记录触发事件的精确控件,是否有像 ASP.Net 中的 ClientId 一样的 WPF UIElement
的唯一标识符?
为了记录我的WPF表单中的用户操作,我添加了一些全局事件处理程序。
我想记录触发事件的精确控件,是否有像 ASP.Net 中的 ClientId 一样的 WPF UIElement
的唯一标识符?
为什么不使用哈希码。
您可以比较值以确保它们是相同的对象,并且使用.GetHashCode()
很容易获取它们。
显然,每次运行程序时都会有所不同,因此实际上这可能是一个不好的想法,除非您想在记录过程每次记录时更新日志。不过仍然是有可能的
我的意思是,您可以在创建日志时为每个对象存储哈希值,但我不知道我是否喜欢这种方式。
看起来我找到了我的问题的答案,答案是否定的,没有办法做到这一点。正如在MSDN中所指出的那样(http://msdn.microsoft.com/en-us/magazine/dd483216.aspx)
请注意,顶级窗口控件定义不包含名称属性。这很重要,因为我们很快将看到,在编写测试自动化时,使用MUIA库获取对控件的引用的简单方法是访问AutomationId属性,该属性由编译器从控件的名称属性生成。没有XAML名称属性的控件将不会收到AutomationId属性。这个想法是考虑应用程序设计问题的特定低级示例,例如安全性、可扩展性和测试自动化的重要性。
你可以通过自定义属性来实现这一点,例如:
你想要记录的UIElement
(例如UserControl):
[UserInterfaceID(ID = "{F436E9B3-C2F6-4CF8-8C75-0A2A756F1C74}")]
public partial class MyUserControl : UserControl
{
InitializeComponent();
// or whatever...
}
[System.AttributeUsage(AttributeTargets.Class)]
public class UserInterfaceIDAttribute : Attribute
{
public Guid ID { get; set; }
}
MyUserControl control = new MyUserControl();
foreach(object att in control.GetCustomAttributes(typeof(UserInterfaceAttribute),false))
{
UserInterfaceAttribute uiAtt = (UserInterfaceAttribute)att;
Guid theID = uiAtt.ID;
}
this.GetCustomAttributes(...)
你只需要添加一个Name
或x:Name
,这样Window
/UserControl
/Page
就会使用指定的名称将控件公开给类的其余部分。
<Window ...>
<Grid>
...
<!-- These controls are named, so you can access them directly by name -->
<Button x:Name="btnMyNamedButton" ... />
<Button Name="btnMyOtherNamedButton" ... />
<!-- This control is not named, so you can not directly access it by name -->
<Button ... />
<Grid>
</Window>
public partial class MyWindow : Window
{
public MyWindow()
{
InitializeComponent();
//btnMyNamedButton can be accessed
//btnMyOtherNamedbutton can also be accessed
//The third button can be accessed, but not directly by name.
}
}
我认为UIElement.Uid
应该可以工作。在XAML中分配它并在代码中访问它。
<Label Uid="FirstName"/>
或者在样式属性中:
<Setter Property="Uid" Value="SecondName"/>
然后在C#代码中引用:
if (Keyboard.FocusedElement is UIElement uiElement) { Debug.WriteLine(this, $"{uiElement.Uid}"); }
我相信,为了记录用户操作,您可以使用UIAutomation树和AutomationElement.AutomationId属性,因为这种方法在所有标准UI控件中都默认支持。许多第三方控件也支持其元素的AutomationId(例如网格单元格)。AutomationId对于创建测试自动化脚本非常有用。