[Solved] How to programmatically click a RANDOM button in WPF?


What I am doing here is getting all the child controls of the wrap panel assuming that you only have buttons on your wrap panel. I then generate random numbers between 0 and the total count of the children and then raising the event. (I am currently editing and formatting my answer)

XAML:

<WrapPanel Name="wrapPanel">
    <Button Name="btnClickMe1" Content="Button" HorizontalAlignment="Left" Margin="166,109,0,0" VerticalAlignment="Top" Width="75" Click="ClickMe1"/>
    <Button Name="btnClickMe12" Content="Button" HorizontalAlignment="Left" Margin="166,109,0,0" VerticalAlignment="Top" Width="75" Click="ClickMe2"/>
</WrapPanel>

C#:

public static int GetRandomNumber(int max)
{
    lock (getrandom) // synchronize
    {
        return getrandom.Next(max);
    }
}

private static readonly Random getrandom = new Random();
private void ClickMe1(object sender, RoutedEventArgs e)
{
    MessageBox.Show("You clicked me 1");
}

private void ClickMe2(object sender, RoutedEventArgs e)
{
    MessageBox.Show("You clicked me 2");
}

private void TestPeformClick(object sender, RoutedEventArgs e)
{
    int index = GetRandomNumber(wrapPanel.Children.Count);
    RoutedEventArgs newEventArgs = new RoutedEventArgs(Button.ClickEvent);
    wrapPanel.Children[index].RaiseEvent(newEventArgs);
}

solved How to programmatically click a RANDOM button in WPF?