Silverlight:将子窗口重新定位到中心

时间:2011-09-06 22:02:46

标签: c# silverlight

子窗口内的内容发生变化,导致我的子窗口丢失了它的中心对齐....内容更改后无论如何都要将子窗口重新定位到中心...我尝试了以下内容不工作:

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

由于

2 个答案:

答案 0 :(得分:8)

ChildWindow模板上存在RenderTransform似乎应该受到指责。 TransformGroup是默认模板的一部分,允许您在窗口中移动。

更改布局后,重置变换是一个黑客攻击:

        //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() }
            };
        }); 

或更自动:

    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,因此您可能需要检查contentRoot.ActualWidth和ActualHeight是否已更改,以确定是否确实需要清除转换。

答案 1 :(得分:0)

代码

public partial class DialogOptions : ChildWindow
{
    public DialogOptions()
    {
        InitializeComponent();

        Loaded += (sender, args) =>
        {
            VerticalAlignment = VerticalAlignment.Top;
            this.SetWindowPosition(new Point(0, 200));
        };
    }
}

延伸:

    public static void SetWindowPosition(this ChildWindow childWindow, Point point)
    {
        var root = VisualTreeHelper.GetChild(childWindow, 0) as FrameworkElement;

        if (root == null)
        {
            return;
        }

        var contentRoot = root.FindName("ContentRoot") as FrameworkElement;

        if (contentRoot == null)
        {
            return;
        }

        var group = contentRoot.RenderTransform as TransformGroup;

        if (group == null)
        {
            return;
        }

        TranslateTransform translateTransform = null;

        foreach (var transform in group.Children.OfType<TranslateTransform>())
        {
            translateTransform = transform;
        }

        if (translateTransform == null)
        {
            return;
        }

        translateTransform.X = point.X;
        translateTransform.Y = point.Y;        
    }