0

我收集了这样的课程:

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>

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

4

2 回答 2

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>

实现aDelegateCommand很简单,这里举个例子

于 2013-09-18T13:22:24.913 回答
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>
于 2013-09-18T13:59:59.780 回答