NoWar
NoWar

Reputation: 37633

Pass data by CommandParameter

I am trying to pass UserName by CommandParameter.

<GridViewColumn   Width="Auto" Header="UserName" >
   <GridViewColumn.CellTemplate>
       <DataTemplate>
          <Button Click="Button_Click" Content="..." CommandParameter="{Binding Path=UserName}"></Button>                                                                                                         </DataTemplate>
    </GridViewColumn.CellTemplate>
</GridViewColumn>

But here I am not sure what do I have to use to catch it...

private void Button_Click(object sender, RoutedEventArgs e)
{
    // How to get UserName  here?
}

Any clue?

Thank you!

Upvotes: 1

Views: 1863

Answers (2)

XamlZealot
XamlZealot

Reputation: 722

If you are going to use the click handler, why not bind the Button's Tag property to UserName? A little more along the lines of what the Tag property was intended than a misuse of Commanding principals.

<Button Click="Button_Click" Content="Button Content" Tag="{Binding UserName}"/>

private void Button_Click(object Sender, RoutedEventArgs e)
{
    var Button = (Button)Sender;
    var UserName = (string)Button.Tag;
}

Upvotes: 2

Snowbear
Snowbear

Reputation: 17274

Best you can do with such approach is this:

private void Button_Click(object sender, RoutedEventArgs e)
{
    var button = (Button) sender;
    var userName = button.CommandParameter;
}

Though it will do the job but it is not how CommandParameter is supposed to be used. CommandParameter is supposed to be passed as parameter to button's command. So if you will use Command instead of handling Button.Click your command will receive your data in its Execute and CanExecute handlers. See samples for commands&buttons in google. Here is first link from google for example: How to use Commands in WPF

Upvotes: 2

Related Questions