0

Learning WPF with MacDonald's "Pro WPF 4.5 in C#," focusing on Ch5, Events. How would I write a generic event handler that works with both Labels and TextBoxes to process the MouseDown event initializing a drag & drop procedure? Here is my TextBox handler:

private void tBSource_MouseDown(object sender, EventArgs e) {
            TextBox tBox = (TextBox)sender;
            DragDrop.DoDragDrop(tBox, tBox.Text, DragDropEffects.Copy);
}

And my Label handler:

private void lblSource_MouseDown(object sender, EventArgs e) {
            Label lbl = (Label)sender;
            DragDrop.DoDragDrop(lbl, lbl.Content, DragDropEffects.Copy);
}

As you can see, I'm using the Content property and the Text property, depending on which object starts the event. If I try to use the same property for both senders, I get build errors (regardless of which I use). If I can avoid duplication, I would be very happy. Should I chunk a conditional out into another function and call that in the handler to determine what property should be used?

SigNet
  • 25
  • 5

1 Answers1

0

you could do something like this:

private void Generic_MouseDown(object sender, EventArgs e)
    {
        object contentDrop = string.Empty;
        //Label inherits from ContentControl so it doesn't require more work to make work for all controls inheriting from ContentControl
        if (sender is ContentControl contentControl)
        {
            //If you don't want to filter other content than string, you can remove this check you make contentDrop an object
            if (contentControl.Content is string)
            {
                contentDrop = contentControl.Content.ToString();
            }
            else
            {
                //Content is not a string (there is probably another control inside)
            }
        }
        else if (sender is TextBox textBox)
        {
            contentDrop = textBox.Text;
        }
        else
        {
            throw new NotImplementedException("The only supported controls for this event are ContentControl or TextBox");
        }
        DragDrop.DoDragDrop((DependencyObject)sender, contentDrop, DragDropEffects.Copy);
    }

Let me know if you have any question

Ostas
  • 839
  • 7
  • 11
  • Very clear and instructional answer, thank you. I do have one question: what if I wanted to catch both TextBoxes and TextBlocks? They do not share a single shared parent object as far as I can tell. Would I need to add another `else if` block to capture TextBlock? I have to admit, I find WPF controls' inheritance structure to be a little obtuse. – SigNet May 20 '20 at 21:17
  • Yes, I checked that as well, I expected Textblock and TextBox to have a shared parent with the TextProperty but since it isn't the case you would have to add another else if block. I found this post really interresting regarding the TextProperty: https://stackoverflow.com/a/15236596/13448212 – Ostas May 20 '20 at 21:52