Powered by MSDN

US - English
NEW! Silverlight 5 is available Learn More

VisualTreeHelper works only in certain click events and... RSS

1 reply

Last post Aug 12, 2009 05:42 AM by lingbing

(0)
  • rajkra

    rajkra

    Member

    35 Points

    41 Posts

    VisualTreeHelper works only in certain click events and not in page load.

    Aug 12, 2009 05:03 AM | LINK

    Here, I have an expander control in which I have header template.  I am trying to find the textblock inside the header template of the expander control from code behind.  so, I am using this piece of code  which will return the value for count as 1 during click event of certain buttons, but I want to access it in page load itself.  Anyways to do it?

     

     click().....In click event

    {

     TextBlock tb = GetTextBlockWithParent(this.Expander2, typeof(TextBlock), "tblCurrentBalanceValue");
                tb.UpdateLayout();
                if (tb != null)
                {
                    tb.Text = "583";
                } 

     }

     

         public TextBlock GetTextBlockWithParent(UIElement parent, Type targetType, string TextBlockName)
            {
                if (parent.GetType() == targetType && ((TextBlock)parent).Name == TextBlockName)
                {
                    return (TextBlock)parent;
                }
                TextBlock result = null;
                int count = VisualTreeHelper.GetChildrenCount(parent);
                for (int i = 0; i < count; i++)
                {
                    UIElement child = (UIElement)VisualTreeHelper.GetChild(parent, i);

                    if (GetTextBlockWithParent(child, targetType, TextBlockName) != null)
                    {
                        result = GetTextBlockWithParent(child, targetType, TextBlockName);
                        break;
                    }
                }
                return result;
            }

     

    This is the definition of it. 

     

     

     

    Raja
  • lingbing

    lingbing

    Contributor

    2249 Points

    406 Posts

    Re: VisualTreeHelper works only in certain click events and not in page load.

    Aug 12, 2009 05:42 AM | LINK

    Hi, this is the control life-cycle issue, in Loaded event, the layout is not updated completedly, so please add your code into the handler of LayoutUpdated event, or if you use Silverlight 3, use the extension method InvokeOnLayoutUpdated, the you can get your code working.

    Regards!

    Ling Bing
    Bei Jing University of Aeronautics and Astronautics
    Bei Jing, China