2015-05-21 70 views
1

給定一個非常基本的WinForms自定義/用戶控件,使用System.Windows.Automation可以操作自定義控件的內置屬性。使用UI自動化框架公開自定義屬性

public object GetPropertyValue(int propertyId) 
     { 
     if (propertyId == AutomationElementIdentifiers.NameProperty.Id) 
      { 
       return "Hello World!"; 
      } 
     } 

我想要做的是暴露在UI自動化如readyState的,上次訪問自定義屬性等

這是可能的:

這是這樣做呢?

回答

2

不,你不能擴展屬性列表,這很複雜,因爲你使用的WinForms具有較差的UI自​​動化支持(它使用IAccessible和網橋等)。

你可以做什麼,雖然是添加一些虛假對象到自動化樹,例如,這裏是一個樣本的WinForms用戶控件,做它:

public partial class UserControl1 : UserControl 
{ 
    public UserControl1() 
    { 
     InitializeComponent(); 

     Button button = new Button(); 
     button.Location = new Point(32, 28); 
     button.Size = new Size(75, 23); 
     button.Text = "MyButton"; 
     Controls.Add(button); 

     Label label = new Label(); 
     label.Location = new Point(49, 80); 
     label.Size = new Size(35, 13); 
     label.Text = "MyLabel"; 
     Controls.Add(label); 

     MyCustomProp = "MyCustomValue"; 
    } 

    public string MyCustomProp { get; set; } 

    protected override AccessibleObject CreateAccessibilityInstance() 
    { 
     return new UserControl1AccessibleObject(this); 
    } 

    protected class UserControl1AccessibleObject : ControlAccessibleObject 
    { 
     public UserControl1AccessibleObject(UserControl1 ownerControl) 
      : base(ownerControl) 
     { 
     } 

     public new UserControl1 Owner 
     { 
      get 
      { 
       return (UserControl1)base.Owner; 
      } 
     } 

     public override int GetChildCount() 
     { 
      return 1; 
     } 

     public override AccessibleObject GetChild(int index) 
     { 
      if (index == 0) 
       return new ValueAccessibleObject("MyCustomProp", Owner.MyCustomProp); 

      return base.GetChild(index); 
     } 
    } 
} 

public class ValueAccessibleObject : AccessibleObject 
{ 
    private string _name; 
    private string _value; 

    public ValueAccessibleObject(string name, string value) 
    { 
     _name = name; 
     _value = value; 
    } 

    public override AccessibleRole Role 
    { 
     get 
     { 
      return AccessibleRole.Text; // activate Value pattern 
     } 
    } 

    // note you need to override with member values, base value cannot always store something 
    public override string Value { get { return _value; } set { _value = value; } } 
    public override string Name { get { return _name; } } 
} 

,這是它如何出現在自動化樹(使用inspect.exe工具):

enter image description here

注意這種技術也支持,因爲它是基於對ValuePattern寫回財產。

+0

這是一個很好的答案,只是爲了確認CustomProp是否會干擾常規的UI元素子結構? –

+0

「干涉」是什麼意思?這是樹中的一個成熟元素,它是一個孩子。 –

+0

是否可以動態地向myCustProp添加子項? –