---
title: "Can I bind event to a button?"  
description: "Can I bind event to a button?"  
author: "Anonymous User"  
published: 2013-09-23  
updated: 2013-09-23  
canonical: https://www.mindstick.com/forum/1500/can-i-bind-event-to-a-button  
category: "wpf"  
tags: ["wpf", "bind event", "button", "wpf event", "mindstick"]  
reading_time: 1 minute  

---

# Can I bind event to a button?

I have [collection](https://www.mindstick.com/articles/1718/collections-in-java) of such classes:

public class class1

{

public double first {get;set;}

public double second {get;set;}

[public void](https://www.mindstick.com/interview/2715/can-we-write-static-public-void-instead-of-public-static-void) divide(object sender, RoutedEventArgs e)

{

first/=2;

second/=2;

}

}

[ObservableCollection](https://www.mindstick.com/forum/1367/difference-between-observablecollection-and-bindinglist-in-wpf)<class1> collection1;

That are displayed using wpf and databinding:

<[Listbox](https://www.mindstick.com/articles/626/listbox-events-in-c-dot-net) ItemsSource="{[Binding](https://www.mindstick.com/blog/146/dynamic-binding-in-c-sharp) collection1}" >

<ListBox.ItemTemplate>

<DataTemplate>

<WrapPanel>

<[TextBox](https://www.mindstick.com/forum/12714/dynamic-textbox-in-gridview) Text="{Binding first}" />

<TextBox Text="{Binding second}" />

<Button [Content](https://www.mindstick.com/articles/13019/get-the-best-content-marketing-pricing-packages-for-your-brand)="Divide" />

</WrapPanel>

</DataTemplate>

</ListBox.ItemTemplate>

My [question](https://www.mindstick.com/blog/23175/how-to-solve-neet-question-paper-in-less-time) is: can I somehow bind each button to it's [instance](https://www.mindstick.com/forum/155658/testing-connection-to-cloud-sql-instance-with-a-mysql-client-from-vm-instance)'s [function](https://www.mindstick.com/articles/13001/multi-statement-table-valued-user-defined-function-in-sql-server) divide?

## Replies

### Reply by Pravesh Singh

Hi Lois,

Assuming you're using a code-behind (.xaml.cs), you can define an event handler like this there:

```
private void DivideButton_Click(object sender,
RoutedEventArgs e) {    var button =(Button)e.Source;  // <-- the specific
button that was clicked    var c1 =(class1)button.DataContext;  // <--
the instance bound to this button    c1.Divide();}
```

## In class1:

```
public void Divide() {    first/=2;    second/=2;}
```

## In XAML:

```
<DataTemplate>    <WrapPanel>        <TextBox Text="{Binding first}" />        <TextBox Text="{Binding second}" />        <Button Content="Divide" Click="DivideButton_Click" />    </WrapPanel></DataTemplate>
```


---

Original Source: https://www.mindstick.com/forum/1500/can-i-bind-event-to-a-button

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
