简体   繁体   English

通过CommandParameter传递数据

[英]Pass data by CommandParameter

I am trying to pass UserName by CommandParameter . 我试图通过CommandParameter传递UserName

<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 CommandParameter is supposed to be passed as parameter to button's command. CommandParameter应该作为参数传递给button的命令。 So if you will use Command instead of handling Button.Click your command will receive your data in its Execute and CanExecute handlers. 因此,如果您将使用Command而不是处理Button.Click您的命令将在其ExecuteCanExecute处理程序中接收您的数据。 See samples for commands&buttons in google. 请参阅Google中的命令和按钮示例。 Here is first link from google for example: How to use Commands in WPF 这是谷歌的第一个链接,例如: 如何在WPF中使用命令

If you are going to use the click handler, why not bind the Button's Tag property to UserName? 如果您要使用单击处理程序,为什么不将Button的Tag属性绑定到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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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