Add parameter to Button click event
Asked Answered
M

4

72

I have a wpf button like this:

<Button Click="button1_Click" Height="23" Margin="0,0,5,0" Name="button1" Width="75">Initiate</Button>

And I want to pass {Binding Code} passed as parameter to the button1_click handler.
How do I go about this?

Disclaimer: really new to WPF

Mori answered 5/1, 2010 at 14:12 Comment(0)
H
154

Simple solution:

<Button Tag="{Binding Code}" ...>

In your handler, cast the sender object to Button and access the Tag property:

var myValue = ((Button)sender).Tag;

A more elegant solution would be to use the Command pattern of WPF: Create a Command for the functionality you want the button to perform, bind the Command to the Button's Command property and bind the CommandParameter to your value.

Headwind answered 5/1, 2010 at 14:18 Comment(1)
The tag will do for now and for more complicated scenarios I will look into the command pattern. ThanksMori
L
20

I'm not overly a fan of 'Tag' so perhaps

<Button Click="button1_Click" myParam="parameter1" Height="23" Margin="0,0,5,0" Name="button1" Width="75">Initiate</Button>

Then accessing via the Attributes.

 void button1_Click(object sender, RoutedEventArgs e)
 {
    var button = sender as Button;
    var theValue = button.Attributes["myParam"].ToString()
 }
Leela answered 28/9, 2012 at 9:44 Comment(2)
The member "myParam" is not recognized or is not accessible.Kirmess
This would work with an attached property, but at that point a command is just as easy.Spinach
S
11

Well there are two ways of doing this:

Cast the DataContext

 void button1_Click(object sender, RoutedEventArgs e)
 {
    var button = sender as Button;
    var code = ((Coupon)button.DataContext).Code;
 }

Or use the Tag property which is a generic state property

 <Button Click="button1_Click" Height="23" Margin="0,0,5,0" Name="button1" Tag="{Binding Code}" />

then

void button1_Click(object sender, RoutedEventArgs e)
{
    var button = sender as Button;
    var code = button.Tag;
}
Surah answered 5/1, 2010 at 14:19 Comment(1)
I would use (Button)sender instead of sender as Button. In the unlikely case that sender is not a button, (Button)sender will throw an InvalidCastException, thereby helping you find the error. Your code, on the other hand, will silently set button to null in that case, causing a NullReferenceException later on.Headwind
D
4

Using Xaml and DataContext

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:DataAndCloudServices"
             x:Class="DataAndCloudServices.MainPage" >

    <StackLayout>
        <!-- Command Implemented In Code Behing -->
        <Button Text="Consuming Web Services Samples" 
                Command="{Binding NavigateCommand}" 
                CommandParameter="{x:Type local:YourPageTypeHere}" >

        </Button>
    </StackLayout>
</ContentPage>

And MainPage Code Behing, this code example is to navigate to another page using the page type as argument, you need to make "YourPageTypeHere" and reference page here.

Then implement code Behind.

using System;
using System.Windows.Input;
using Xamarin.Forms;

namespace DataAndCloudServices
{
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();

            NavigateCommand = new Command<Type>(
              async (Type pageType) =>
              {
                  Page page = (Page)Activator.CreateInstance(pageType);
                  await Navigation.PushAsync(page);
              });

            this.BindingContext = this;
        }
        public ICommand NavigateCommand { private set; get; }
    }
}

Also in your App class need a Instance of NavigationPage in MainPage to Navigate (For this example)

public App ()
{
    InitializeComponent();

    MainPage = new NavigationPage(new MainPage());
}

It is for xamarin forms, But It is similar for WPF Projects.

Command could be changed with for WPF and Xamarin: "https://mcmap.net/q/275886/-relaycommand-parameter-passing-in-xamarin"

Diedrediefenbaker answered 29/6, 2018 at 16:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.