我有这个代码可以通过编程方式按下按钮,但我希望有一个版本适用于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.
}
答案 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