简体   繁体   English

Silverlight:使用UI自动化模拟RadioButton Click事件吗?

[英]Silverlight: Simulate RadioButton Click event using UI Automation?

In Silverlight, both the Button and the RadioButton controls have a Click event, since they inherit from System.Windows.Controls.Primitives.ButtonBase . 在Silverlight中,由于ButtonRadioButton控件都继承自System.Windows.Controls.Primitives.ButtonBase ,因此它们都具有Click事件。

If we want to simulate this Click event for a Button , we can use the ButtonAutomationPeer class, like so (given a button called myButton ): 如果要模拟Button Click事件,则可以使用ButtonAutomationPeer类,就像这样(给定名为myButton的按钮):

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

However, when we try to do the same thing for a RadioButton , we discover that the RadioButtonAutomationPeer class does not implement IInvokeProvider (so we can't call Invoke() ). 但是,当我们尝试对RadioButton做同样的事情时,我们发现RadioButtonAutomationPeer类未实现IInvokeProvider (因此我们无法调用Invoke() )。 Is there some other way we can cause the Click event for a RadioButton to be fired? 还有其他方法可以导致触发RadioButtonClick事件吗?

Try this: 尝试这个:

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

You'll need to know your desired toggle state (On, Off, or Indeterminate). 您需要知道所需的切换状态(打开,关闭或不确定)。 Or if you just want to toggle to a different state, strike the while loop just call Toggle. 或者,如果您只想切换到其他状态,只需调用Toggle即可触发while循环。

Obviously this isn't the exact same thing as a click. 显然,这与单击并不完全相同。 If you've bound the radio button to a command, you might be forced to be a little more explicit and do something like this to get your automation to work: 如果将单选按钮绑定到命令,则可能会被迫更加明确,并执行以下操作以使自动化工作:

<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>

Using the Blend SDK (that's the "i:" xmlns), you're invoking a command when the RadioButton is checked. 使用Blend SDK(即“ i:” xmlns),您在选中RadioButton时正在调用命令。 Personally I'd do that approach even without automation over just binding a command to a RadioButton: it's not clear when the command executes with a binding, but the triggers add some clarity and remove the need for me to think the next time I look at the code. 就我个人而言,即使没有自动将命令绑定到RadioButton的方式,我也会采用这种方法:尚不清楚何时使用绑定执行命令,但是触发器增加了一些清晰度,并消除了我下次查看时的思考编码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM