简体   繁体   中英

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!

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

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM