0

I have the following style in my XAML:

<Style x:Key="NumberButton" TargetType="Button">
    <Setter Property="Width" Value="Auto"/>
    <Setter Property="Height" Value="Auto"/>
    <Setter Property="Margin" Value="2"/>
    <Setter Property="ContentTemplate">
        <Setter.Value>
            <DataTemplate>
                <Label Content="{Binding}" FontSize="20" FontFamily="Consolas"/>
            </DataTemplate>
        </Setter.Value>
    </Setter>
    <EventSetter Event="Click" Handler="OnClicked"/>
</Style>

I create 10 <Button>'s and I apply this style to each of them. The Content="" of each button is set to a number 0-9. I'd like to create an event handler for each of these buttons (through the style itself) that will pass in the value of the Content property to the event handler in the code behind.

I'm still new to WPF so any help would be greatly appreciated. Thank you!

void.pointer
  • 24,859
  • 31
  • 132
  • 243
  • 1
    Casting the event sender in the event handler to button and reading content might work, no? See this: http://stackoverflow.com/questions/2006507/add-parameter-to-button-click-event – hschne Dec 25 '13 at 23:17

2 Answers2

1

Try this

<Style x:Key="NumberButton" TargetType="Button">
<Setter Property="Width" Value="Auto"/>
<Setter Property="Height" Value="Auto"/>
<Setter Property="Margin" Value="2"/>
<Setter Property="Tag" Value="{Binding}"/>
<Setter Property="ContentTemplate">
    <Setter.Value>
        <DataTemplate>
            <Label Content="{Binding}" FontSize="20" FontFamily="Consolas"/>
        </DataTemplate>
    </Setter.Value>
</Setter>
<EventSetter Event="Click" Handler="OnClicked"/>
</Style>

Then in code behind

 void OnClicked(object sender, RoutedEventArgs e)
 {
   var button = sender as Button;
   var content= button.Tag; // this is the value you want
 }
Mohd Ahmed
  • 1,422
  • 13
  • 27
1

You can get the Content from sender button:

void OnClicked(object sender, RoutedEventArgs e)
{
    string content = ((Button)sender).Content.ToString();
}

Call ToString() on Content since its of type object.

Rohit Vats
  • 79,502
  • 12
  • 161
  • 185