子窗口内的内容会发生变化,这会导致我的子窗口失去它的中心对齐....内容更改后,无论如何都要将子窗口重新定位到中心...我尝试了以下操作并且它不起作用:
this.horizontalalignment = horizontalalignment.center;
this.verticalalignment = verticalalignment.center;
Run Code Online (Sandbox Code Playgroud)
谢谢
似乎应该责怪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() }
};
});
Run Code Online (Sandbox Code Playgroud)
或更自动:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
经常调用LayoutUpdated,因此您可能需要检查contentRoot.ActualWidth和ActualHeight是否已更改,以确定是否确实需要清除转换.