Silverlight:使用UI Automation模拟RadioButton Click事件?

时间:2011-12-10 13:37:49

标签: c# silverlight silverlight-4.0 silverlight-3.0 ui-automation

在Silverlight中,ButtonRadioButton控件都有Click个事件,因为它们是从System.Windows.Controls.Primitives.ButtonBase继承的。

如果我们要为Click模拟此Button事件,我们可以使用ButtonAutomationPeer类,如此(给定一个名为myButton的按钮):

ButtonAutomationPeer peer = new ButtonAutomationPeer(myButton);
IInvokeProvider ip = (IInvokeProvider)peer;
ip.Invoke();

但是,当我们尝试对RadioButton执行相同操作时,我们发现RadioButtonAutomationPeer类未实现IInvokeProvider(因此我们无法调用Invoke() })。还有其他一些方法可以导致Click的{​​{1}}事件被解雇吗?

1 个答案:

答案 0 :(得分:0)

试试这个:

RadioButtonAutomationPeer peer = new RadioButtonAutomationPeer(myRadioButton);
IToggleProvider tp = (IToggleProvider) peer;
while (tp.ToggleState != targetToggleState)
{
   tp.Toggle();
}

您需要知道所需的切换状态(开,关或不确定)。或者,如果您只想切换到其他状态,请点击while循环,只需调用Toggle。

显然,这与点击完全不同。如果你将单选按钮绑定到一个命令,你可能会被迫更加明确,并做一些这样的事情来让你的自动化工作:

<RadioButton ... (don't set the Command property)>
  <i:Interaction.Triggers>
    <i:EventTrigger EventName="Checked">
      <i:InvokeCommandAction Command="{Binding MyCommand}" />
    </i:EventTrigger>
  </i:Interaction.Triggers>
</RadioButton>

使用Blend SDK(即“i:”xmlns),在选中RadioButton时调用命令。就个人而言,即使没有自动化而只是将命令绑定到RadioButton,我也会采用这种方法:不清楚命令何时使用绑定执行,但是触发器增加了一些清晰度,并且在下次我看到时无需考虑代码。