locked
How to assign a Event handler dynamically to a dynamically created control

    Question

  • Hi,

         In a Win8 metro app (in XAML and C++), I need to add dynamic Image controls and need to handle the Mouse Pointer Entered events:

         My code is as follows:

    void Application5::BlankPage::Button_Click_2(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
    {

    Image^ img3 = ref new Image();

    Thickness margin1 =  img3->Margin;

    img3->Source = ref new BitmapImage(ref new Uri(BaseUri->AbsoluteUri, "VideoChat1.png"));

    margin1.Left = 120;

    margin1.Top = 220;

    img3->Height=100;

    img3->Width=100;

    img3->Margin = margin1;

    BlankPage::grd1->Children->Append(img3);

    //The following line doesn't help to add an event handler

    img3->PointerEntered += ref new Windows::UI::Xaml::Input::PointerEventHandler(this, &BlankPage::OnMouseOver);

    //See the following line. This Img2 is created during Design time and by using the following code we can successfully

    // add the event handler

    Img2->PointerEntered += ref new Windows::UI::Xaml::Input::PointerEventHandler(this, &BlankPage::OnMouseOver);

    }

    void Application5::BlankPage::OnMouseOver(Platform::Object^ sender, Windows::UI::Xaml::Input::PointerEventArgs^ e)
    {
     String^ s =sender->ToString();
     auto i =10;
    }

    =======================

    When we run the sample application, we can see one button control and an Image control (Img2) on the screen. If we move the mouse over the Image control (Img2) nothing is happening or no PointerEntered() event triggered. When we press the Button the above code will be executed and we can a new Image control (Img3) also on the screen. When we move the mouse over Img2 now, the event is triggered(put a breakpoint to verify), but nothing is happening when we move mouse over Img3 (which is created dynamically).

    What could be the problem here?

    -Pradeep

    Friday, April 27, 2012 12:38 PM

All replies

  • I tested your code. But I can't reproduce your problem. It works well in my side. So could you please share your project?

    Best Regards,

    Han Xia


    Saturday, April 28, 2012 5:11 AM
    Moderator