Home > DeveloperSection > Forums > Can I bind event to a button?
lois waisbrooker
lois waisbrooker

Total Post:70

Points:494
Posted on    September-23-2013 8:02 AM

 WPF
Ratings:


 1 Reply(s)
 641  View(s)
Rate this:

I have collection of such classes:

public class class1

{                 

    public double first {get;set;}

    public double second {get;set;}

    public void divide(object sender, RoutedEventArgs e)

    {

        first/=2;

        second/=2;

    }

}

ObservableCollection<class1> collection1;

That are displayed using wpf and databinding:

<Listbox ItemsSource="{Binding collection1}" >

<ListBox.ItemTemplate>

    <DataTemplate>

        <WrapPanel>

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

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

            <Button Content="Divide" />

        </WrapPanel>

    </DataTemplate>

</ListBox.ItemTemplate>

My question is: can I somehow bind each button to it's instance's function divide?



Pravesh Singh

Total Post:411

Points:2881
Posted on    September-23-2013 8:31 AM

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>


Don't want to miss updates? Please click the below button!

Follow MindStick