locked
Measure an element not in the visual tree RRS feed

  • General discussion

  • So I need to measure an element outside of the visual tree.  Basically, I am trying to create a grid of a fixed cell size and this is how I decided to compute the cell size.

     In my case I am measuring a content control.  Problem is, depending on how I created the ContentControl and when I call Measure, I get different answers..

     Here is some example code:

      

            private void RunTest()
            {
                ContentControl[] contentControls = new ContentControl[3];
    
                contentControls[0] = new ContentControl();
                String xaml = "<ContentControl xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" />";
                contentControls[1] = XamlReader.Load(xaml) as ContentControl;
                contentControls[2] = Resources["TestControl"] as ContentControl;
    
                DataTemplate dt = (DataTemplate)Resources["MyDataTemplate"]; 
                foreach (ContentControl cc in contentControls)
                {
                    cc.Content = "Hello World";
                    cc.ContentTemplate = dt;
                    cc.Measure(new Size(Double.PositiveInfinity, double.PositiveInfinity));
                    cc.UpdateLayout();
    
                    System.Diagnostics.Debug.WriteLine(cc.DesiredSize);
                }
            }

     Of course, this assumes that you have the appropriate resources defined.

    If I call this in a Page's constructor, I get the following answers:

    contentControls[0].DesiredSize = 0,16   //this one is new ContentControl()

    contentControls[1].DesiredSize = 19, 24  //XamlReader.Load

    contentControls[2].DesiredSize = 19, 24  //Resources

    Also, the visual tree for contentControls[0] is different from contentControls[1] and contentControls[2].  (It has a Grid as its child, the others have a ContentPresenter).

    If I call this after the page has drawn once, (say in a mouseenter event handler) I get different answers

    contentControls[0].DesiredSize = 0,16  //new ContentControl()

    contentControls[1].DesiredSize = 19, 24  //XamlReader.Load

    contentControls[2].DesiredSize = 73, 24   //Resources -- this is the right answer!

    Ideally, I would just be able to do new ContentControl... Anyone know why I get all the different answers.

     

    Thursday, December 18, 2008 9:47 AM