CAN I BIND EVENT TO A BUTTON?

lois waisbrooker

Total Post:70

Points:494
Posted by  lois waisbrooker
WPF
 960  View(s)
Ratings:
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?

  1. Pravesh Singh

    Post:412

    Points:2888
    Re: Can I bind event to a button?

    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>

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!