Get a button in itemscontrol and add eventhandler to its click event

Posted by rockdale on Stack Overflow See other posts from Stack Overflow or by rockdale
Published on 2010-06-01T17:44:48Z Indexed on 2010/06/01 18:23 UTC
Read the original article Hit count: 295

Filed under:

I have a custom control shows a customer info with an itemscontrol shows this customer's invoices. within the itemscontrol, I have button, in my code behind I want to wire the button's click event to my host window, but do now know how.

    //public event RoutedEventHandler ViewDetailClick;


    public static readonly RoutedEvent ButtonViewClickEvent = EventManager.RegisterRoutedEvent(
                                    "ButtonViewClick",
                                    RoutingStrategy.Bubble, 
                                    typeof(RoutedEventHandler), 
                                    typeof(custitem));



    public event RoutedEventHandler ButtonViewClick
    {
        add { AddHandler(ButtonViewClickEvent, value); }
        remove {RemoveHandler(ButtonViewClickEvent, value);}
    }


public override void OnApplyTemplate()
    {
        base.OnApplyTemplate();

        this.lstInv = GetTemplateChild("lstInv") as ItemsControl;
        lstInv.ItemContainerGenerator.StatusChanged += new EventHandler(ItemContainerGenerator_StatusChanged);

    }


    private void ItemContainerGenerator_StatusChanged(object sender, EventArgs e)
    {
        if (lstInv.ItemContainerGenerator.Status == System.Windows.Controls.Primitives.GeneratorStatus.ContainersGenerated)
        {
            lstInv.ItemContainerGenerator.StatusChanged -= ItemContainerGenerator_StatusChanged;
            for (int i = 0; i < this.lstInv.Items.Count; i++)
            {
                ContentPresenter c = lstInv.ItemContainerGenerator.ContainerFromItem(lstInv.Items[i]) as ContentPresenter;


                DataTemplate dt = c.ContentTemplate;


                Grid grd = dt.LoadContent() as Grid;

                Button btnView = grd.FindName("btnView") as Button;
                if (btnView != null)
                {
                    btnView.Click += new RoutedEventHandler(ButtonView_Click);
                    //btnView.Click+=  delegate(object senderObj, RoutedEventArgs eArg)
                    //{
                    //    if (this.ViewDetailClick != null)
                    //    {
                    //        this.ViewDetailClick(this, eArg);
                    //    }
                    //};
                }

}

    private void ButtonView_Click(object sender, RoutedEventArgs e)
    {
        MessageBox.Show("clicked");
        //e.RoutedEvent = ButtonViewClickEvent;
        //e.Source = sender;
        //RaiseEvent(e);
    }

I succeed getting the btnView, then attach the click event, but the click event never get fired.

Thanks in advance -rockdale

© Stack Overflow or respective owner

Related posts about wpf-controls