Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Silverlight: reposition child window to center

Tags:

c#

silverlight

The content inside the child window changes, which causes my child window to lose it's center alignment.... After the content has changed is there anyway to reposition the child window to center... I tried the following and it did not work:

this.horizontalalignment = horizontalalignment.center;
this.verticalalignment = verticalalignment.center;

Thanks

like image 829
Ryan Avatar asked Jan 19 '23 19:01

Ryan


1 Answers

The presence of a RenderTransform on the ChildWindow template seems to be to blame. The TransformGroup is part of the default template to allow you to move around the window.

Here is a hack to reset the transform after you change the layout:

        //after you do some change to the childwindow layout
        sp.Children.Add(new Button() { Content = "a" });

        Dispatcher.BeginInvoke(() =>
        {
            //reset the transform to zero
            (this.GetTemplateChild("ContentRoot") as Grid).RenderTransform = new TransformGroup()
            {
                Children = { new ScaleTransform(), new SkewTransform(), new RotateTransform(), new TranslateTransform() }
            };
        }); 

or more automatically:

    public override void OnApplyTemplate()
    {
        base.OnApplyTemplate();
        var contentRoot = this.GetTemplateChild("ContentRoot") as FrameworkElement;
        contentRoot.LayoutUpdated += contentRoot_LayoutUpdated;
    }

    void contentRoot_LayoutUpdated(object sender, EventArgs e)
    {
        var contentRoot = this.GetTemplateChild("ContentRoot") as FrameworkElement;
        var tg = contentRoot.RenderTransform as TransformGroup;
        var tts = tg.Children.OfType<TranslateTransform>();
        foreach (var t in tts)
        {
            t.X = 0; t.Y = 0;
        }
    }

LayoutUpdated gets called often, so you may want to check if contentRoot.ActualWidth and ActualHeight changed to see if you really need to wipe out the transform.

like image 85
foson Avatar answered Jan 21 '23 09:01

foson