如何以编程方式推送ToggleButton?

时间:2012-04-13 21:01:43

标签: c# wpf ui-automation

我有这个代码可以通过编程方式按下按钮,但我希​​望有一个版本适用于ToggleButton。

public static void PushButton(Button b)
{
     ButtonAutomationPeer peer = new ButtonAutomationPeer(b);
     System.Windows.Automation.Provider.IInvokeProvider invokeProv = peer.GetPattern(PatternInterface.Invoke) as System.Windows.Automation.Provider.IInvokeProvider;
     invokeProv.Invoke();
}

所以我尝试了ToggleButtonAutomationPeer ......

public static void PushButton(ToggleButton b)
{
  ToggleButtonAutomationPeer peer = new ToggleButtonAutomationPeer(b);
  System.Windows.Automation.Provider.IInvokeProvider invokeProv = peer.GetPattern(PatternInterface.Invoke) as System.Windows.Automation.Provider.IInvokeProvider;

//But invokeProv is null.   Peer is ok. 
}

2 个答案:

答案 0 :(得分:7)

您可以使用Toggle Button Automation Peer

public static void PushToggleButton(ToggleButton b)
{
    ToggleButtonAutomationPeer peer = new ToggleButtonAutomationPeer(b);
    System.Windows.Automation.Provider.IToggleProvider toggleProvider = peer.GetPattern(PatternInterface.Toggle) as System.Windows.Automation.Provider.IToggleProvider;
    toggleProvider.Toggle();
}

答案 1 :(得分:0)

另一种方法是在按钮上引发ClickEvent。

//check that the button is untoggled
if (this.MyToggleButton.IsChecked == false)
{
    //set button toggled
    this.MyToggleButton.IsChecked = true;
    //then raise a click evt
    this.MyToggleButton.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
}

假设MyToggleButton是代码隐藏中定义的ToggleButton或xaml中通过x:Name

定义的sort