派生的异步委托调用了两次

时间:2014-07-01 09:34:41

标签: c# asynchronous windows-runtime async-await

我正在尝试重用我的自定义控件,在派生控件中覆盖一些事件处理程序。

代码如下:

public partial class ControlBase : UserControl {
public ControlBase() {
        this.InitializeComponent();
        //Buttons
        PickFileButton.Click += pickFile;
}

protected virtual async void pickFile(object sender, RoutedEventArgs e) {

        var picker = new FileOpenPicker();
        picker.SuggestedStartLocation = PickerLocationId.VideosLibrary;
        picker.FileTypeFilter.Add(".wmv");
        picker.FileTypeFilter.Add(".mp4");

        var file = await picker.PickSingleFileAsync();

        if (file == null) return;
        IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.Read);

        inputFile = file;
        InputVideoElement.SetSource(stream, file.ContentType);

    }
}

public sealed partial class DerivedControl : ControlBase {

        public DerivedControl() {
            this.InitializeComponent();

            PickFileButton.Click += pickFile;
        }
//This handler called twice
protected async override void pickFile(object sender, RoutedEventArgs e) {
        base.pickFile(sender, e);
        //some other actions
}

当我尝试调试它时,我看到以下内容: 当我单击派生控件上的按钮时,它会调用override void pickFile(),它调用基本实现。在基本方法pickFile()执行财富var file = await picker.PickSingleFileAsync();,然后,派生处理程序pickFile()第二次调用,操作再次重复var file = await picker.PickSingleFileAsync();,之后我得到{{1} }。

与基本控制按钮相同的操作可以正常工作。可能是什么问题?提前致谢

1 个答案:

答案 0 :(得分:3)

您要添加Click事件处理程序两次:一次在DerivedControl构造函数中,一次在ControlBase构造函数中。

如果您只需要一个处理程序(正如我所期望的那样),只需删除DerivedControl构造函数中的订阅。您的重写方法仍将被调用,因为ControlBase构造函数中的订阅只是一个委托,它将虚拟地调用该方法。

相关问题