我可以将事件绑定到按钮吗?

时间:2013-09-18 13:15:55

标签: c# wpf data-binding

我收集了这样的课程:

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;

使用wpf和数据绑定显示:

<Listbox ItemsSource="{Binding collection1}" >
<ListBox.ItemTemplate>
    <DataTemplate>
        <WrapPanel>
            <TextBox Text="{Binding first}" />
            <TextBox Text="{Binding second}" />
            <Button Content="Divide" />
        </WrapPanel>
    </DataTemplate>
</ListBox.ItemTemplate>

我的问题是:我可以以某种方式将每个按钮绑定到它的实例的功能划分上吗?

2 个答案:

答案 0 :(得分:4)

您可以使用命令执行此操作。

假设您有一个DelegateCommand类(源自ICommand):

public class class1
{
    public double first {get;set;}
    public double second {get;set;}

    public DelegateCommand DivideCommand{get;set;}

    public class1()
    {
         DivideCommand = new DelegateCommand(this.Divide)
    }

    private void Divide(object parameter)
    {
        first/=2;
        second/=2;
    }
}

然后将命令绑定到按钮:

<Listbox ItemsSource="{Binding collection1}" >
<ListBox.ItemTemplate>
    <DataTemplate>
        <WrapPanel>
            <TextBox Text="{Binding first}" />
            <TextBox Text="{Binding second}" />
            <Button Content="Divide" Command="{Binding DivideCommand}" />
        </WrapPanel>
    </DataTemplate>
</ListBox.ItemTemplate>

实施DelegateCommand非常简单,here an example

答案 1 :(得分:1)

我会用Commands解决这个问题,但你可以使用公共事件处理程序,因为事件源可以通过EventArgs获得。假设你正在使用代码隐藏(.xaml.cs),你可以在那里定义一个这样的事件处理程序:

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();
}

class1

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

在XAML中:

<DataTemplate>
    <WrapPanel>
        <TextBox Text="{Binding first}" />
        <TextBox Text="{Binding second}" />
        <Button Content="Divide" Click="DivideButton_Click" />
    </WrapPanel>
</DataTemplate>