locked
How do I assign an event handler for a Shape object programmatically?

    Question

  • Hi, I am dynamically creating Xaml shapes and I'm unable to figure out how to bind event handlers to them programmatically.  I started with a statically created shape and used the property manager in VS to create a callback for me.  Now I want to use that same callback for all my dynamically created shapes, but I'm struggling with the syntax and I can't find any examples of this.  Here's my best guess:

    newEllipse->PointerMoved =

    gcnew Windows::UI::Xaml::Input::PointerEventHandler(this, &Application1::MainPage::CircleMoved);

    This compiles, but I get a runtime error at this line.  For whatever reason I can't catch the exception so I don't have much of a clue as to what is wrong.  Is there an obvious problem with what I'm trying to do?  Thanks.


    DerekMuk

    Saturday, February 18, 2012 12:28 AM

Answers

  • Hi Derek,

    I wouldn't expect that to compile. Gcnew is used in C++/CLI but shouldn't be valid in C++/Cx. You also need to add the callback to the event collection not assign it. A trick for figuring out the syntax of something you generated in the Xaml editor is to look for the generated cpp file in the project's Debug directory where the InitializeComponent call is implemented. It will be named something like "MainPage.g.cpp" and will load the xaml, assign any named shapes to their associated variables, and connect up any event handlers defined in Xaml.

    The one you want will look something like:

    safe_cast<Windows::UI::Xaml::UIElement^>(pTarget))->PointerPressed += ref new Windows::UI::Xaml::Input::PointerEventHandler(this, &MainPage::rect1_PointerPressed)

    --Rob

    Saturday, February 18, 2012 12:43 AM
    Owner

All replies

  • Hi Derek,

    I wouldn't expect that to compile. Gcnew is used in C++/CLI but shouldn't be valid in C++/Cx. You also need to add the callback to the event collection not assign it. A trick for figuring out the syntax of something you generated in the Xaml editor is to look for the generated cpp file in the project's Debug directory where the InitializeComponent call is implemented. It will be named something like "MainPage.g.cpp" and will load the xaml, assign any named shapes to their associated variables, and connect up any event handlers defined in Xaml.

    The one you want will look something like:

    safe_cast<Windows::UI::Xaml::UIElement^>(pTarget))->PointerPressed += ref new Windows::UI::Xaml::Input::PointerEventHandler(this, &MainPage::rect1_PointerPressed)

    --Rob

    Saturday, February 18, 2012 12:43 AM
    Owner
  • Hi Rob,

    Thank you for your response.  That worked great, and I've removed all references to 'gcnew' as well.  And thanks for the tip about MainPage.g.cpp - I have a feeling I'll be relying on that a lot!

    -Derek

    Wednesday, February 22, 2012 12:32 PM