How to use a button x:Name or something to indicate button

467 Views Asked by At

I have a problem. I have to do app for college, guitar emulator, my idea was to put each fret as a button, and implement the color change function to understand which fret (button) is clamped (pressed)

var button = (Button)sender;
_buttonLastPressed = button;
var parent = (Grid)button.Parent;
var index = parent.Children.IndexOf(strip1_1);
var str = Math.Floor((decimal)(index + 1) / 20);
for (int i = 0; i < 20; i++)
{
    var element = (Button)parent.Children[i + Convert.ToInt32(str) * 20];
    element.Background = Brushes.White;
}
button.Background = Brushes.Blue;

This option works well, but the problem arose that I do not know how to get some information from the button in order to use it on what sound to play (so that the program understands which button is pressed). I believe that it was possible to somehow use the DataContext, but I cannot imagine in my head how to do it more competently

For the tip, there are six strings, I decided to declare each string as grid, and in each grid there are 20 frets (buttons), you can hold down only one of all 20

XAML:

<Button x:Name="strip1_1" Content="" HorizontalAlignment="Left" Margin="2,1,0,0" VerticalAlignment="Top" Width="22" Height="4" Click="Strip1_Click" BorderBrush="Black"/>
<Button x:Name="strip1_2" Content="" HorizontalAlignment="Left" Margin="37,1,0,0" VerticalAlignment="Top" Width="22" Height="4" Click="Strip1_Click" BorderBrush="Black"/>
1

There are 1 best solutions below

0
Standard_101 On BEST ANSWER

A possible solution could be to use the Click property of each button which references a different method.

<Button Click="DoSomething_OnClick"/>

and in the code-behind:

private void DoSomething_OnClick(object sender, RoutedEventArgs e)
{
    // Your code here
}

You could use this to have 20 different methods. This way, you know exactly which button called which method.