C#WPF单击随机按钮

时间:2018-06-05 14:28:14

标签: c# wpf button random click

我在WPF上有多个执行Click方法的按钮

 <Grid Margin="0,0,490,170">
    <Grid.RowDefinitions>
        <RowDefinition Height="0*"/>
        <RowDefinition Height="18*"/>
        <RowDefinition/>
    </Grid.RowDefinitions>
    <Button x:Name="button00" HorizontalAlignment="Left" Height="82" Margin="0,1,-114,-7" Grid.RowSpan="3" VerticalAlignment="Top" Width="114" Click="Button_Click"/>
    <Button x:Name="button02" Content="" HorizontalAlignment="Left" Height="82" Margin="228,0,-342,-7" Grid.RowSpan="3" VerticalAlignment="Bottom" Width="114" Click="Button_Click"/>
    <Button x:Name="button01" Content="" HorizontalAlignment="Left" Height="82" Margin="114,1,-228,-7" Grid.RowSpan="3" VerticalAlignment="Top" Width="114" Click="Button_Click" />
...
</Grid>

我的点击就是这个

private void Button_Click(object sender, RoutedEventArgs e)
{
    var button = sender as Button;
    methodDoingStuff(button);
}

我试图自动化该计算机可以随机点击按钮。 喜欢这个

Random rnd = new Random();
int x = rnd.Next(2);
int y = rnd.Next(2);
Button btn = new Button();
btn.Name = "button" +(x.ToString() + y.ToString());
Button_Click(btn);

但我似乎无法做到这一点。 我有什么技巧可以做那种事吗?

3 个答案:

答案 0 :(得分:3)

试试这个:

Button[] allButtons = grid.Children.OfType<Button>().ToArray();
Random rnd = new Random();
int x = rnd.Next(0, allButtons.Length);
Button btn = allButtons[x];
btn.RaiseEvent(new RoutedEventArgs(ButtonBase.ClickEvent));

......其中&#34;网格&#34;是XAML中x:Name的{​​{1}}:

Grid

答案 1 :(得分:0)

尝试使用以下代码:

Random rnd = new Random();
            int x = 0;
            int y = rnd.Next(2);
            var buttonName = "button" + (x.ToString() + y.ToString());
            var buttonControl = this.FindName(buttonName) as Button;
            if (buttonControl != null)
            {
                buttonControl.RaiseEvent(new RoutedEventArgs(Button.ClickEvent, buttonControl));
            }

答案 2 :(得分:0)

您可以创建一个包含对按钮的引用的对象列表。

List<Button> buttonList = new List<Button> {button00, button01, button02};

然后做这样的事情:

Random rnd = new Random();
int selection = rnd.Next(0, 3);
buttonList[selection].RaiseEvent(new RoutedEventArgs(ButtonBase.ClickEvent));