WPFでWinFormsのButtonのPerformClickと同じようなことを実施
namespace WpfButtonPerformClick
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using WpfButtonPerformClick.Extensions;
/// <summary>
/// MainWindow.xaml の相互作用ロジック
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void btn1_Click(object sender, RoutedEventArgs e)
{
this.FindByName<Button>("btn2").PerformClick();
}
private void btn2_Click(object sender, RoutedEventArgs e)
{
DataContext = "Button 2 Clicked.";
}
}
}
<Window x:Class="WpfButtonPerformClick.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
Title="MainWindow"
Height="350"
Width="525">
<Window.DataContext>
<sys:String>hello world</sys:String>
</Window.DataContext>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition />
</Grid.RowDefinitions>
<StackPanel Grid.Row="0" Orientation="Horizontal">
<StackPanel.Resources>
<Style TargetType="Button">
<Setter Property="Margin" Value="10" />
<Setter Property="Height" Value="40" />
<Setter Property="Width" Value="100" />
</Style>
</StackPanel.Resources>
<Button Name="btn1" Content="Button 1" Click="btn1_Click" />
<Button Name="btn2" Content="Button 2" Click="btn2_Click" />
</StackPanel>
<DockPanel Grid.Row="1" LastChildFill="True">
<TextBlock Text="{Binding Path=.}" FontSize="40" TextAlignment="Center" VerticalAlignment="Center" />
</DockPanel>
</Grid>
</Window>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
namespace WpfButtonPerformClick.Extensions
{
public static class FrameworkElementExtensions
{
public static T FindByName<T>(this FrameworkElement self, string name) where T : FrameworkElement
{
return self.FindName(name) as T;
}
}
}
namespace WpfButtonPerformClick.Extensions
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Automation.Peers;
using System.Windows.Automation.Provider;
using System.Windows.Controls;
public static class ButtonExtensions
{
public static void PerformClick(this Button self)
{
//
// WinFormsでいうPerformClickを実行.
// System.Windows.Automation.Peers
// System.Windows.Automation.Provider
// 名前空間が必要。
//
// IInvokeProviderインターフェースは、UIAutomationProvider.dll
// の参照設定が追加で必要となる。
//
var peer = new ButtonAutomationPeer(self);
var provider = peer.GetPattern(PatternInterface.Invoke) as IInvokeProvider;
provider.Invoke();
}
}
}