Derived async delegate called twice

I am trying to reuse my custom control, overriding some event handlers in derived control.

The code is like the follows:

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
}

When I am trying to debug it, I see the follows: When I click the button on derived control, it calls override void pickFile(), which calls base implementation. In base method pickFile() execution riches var file = await picker.PickSingleFileAsync();, and then, derived handler pickFile() called the second time and the actions repeat until var file = await picker.PickSingleFileAsync();again, after that I get System.UnauthorizedAccessException.

Tha same action with base control button works fine. What might be the problem? Thanks in advance

Jon Skeet
people
quotationmark

You're adding the Click event handler twice: once in the DerivedControl constructor, and once in the ControlBase constructor.

If you only want a single handler (as I'd expect), just remove the subscription within the DerivedControl constructor. Your overridden method will still be called, because the subscription in the ControlBase constructor is just a delegate which will invoke the method virtually.

people

See more on this question at Stackoverflow