1

好的,所以我有一个弹出窗口(在程序正常运行期间)应用户的请求显示一些特定于上下文的信息。这个窗口恰好有很多元素,所以加载需要 0.5 - 1 秒。但是,由于我希望此窗口根据上下文包含几种不同类型的信息,因此其内容的宽度和高度可能会有所不同。因此,我将 SizeToContent 值设置为“WidthAndHeight”,以允许窗口根据绑定的任何内容调整大小。

但是,由于窗口需要一些时间来加载,所以用户首先会看到一个小的方形窗口,然后在所有内容渲染后看到全尺寸窗口。我想避免让用户在完全加载之前看到小窗口。

有没有办法让窗口在完全渲染后才显示?

我尝试过的事情:

  • 将窗口的可见性设置为“隐藏”,然后在 ContentRendered 事件处理程序中将其设置为“可见”:该窗口从不显示。

  • 将窗口的不透明度设置为 0,然后在 ContentRendered 事件处理程序中将其设置为 1:窗口本身的内容的不透明度设置为 0,然后设置为 1。

更新:又一次尝试

我还尝试在 XAML 中将 Window.WindowState 设置为“最小化”,然后在 ContentRendered 事件处理程序中将其设置为“正常”。这似乎部分起作用,尽管窗口本身的宽度大于应有的宽度。更糟糕的是,窗口中的内容似乎根据窗口的正确大小呈现,然后窗口自身变大而没有重新呈现内容。因此,内容不在窗口的中心,我们在内容的右侧有一个令人讨厌的黑色矩形,表示窗口的正确大小与当前(更大)大小之间的差异。当我通过抓住窗口边缘手动调整窗口大小时,内容会正确重新渲染,一切看起来都很好。但是我如何强制在代码中重新渲染呢?Window.UpdateLayout() 不起作用。

4

3 回答 3

1

好的,我找到了一个可行的解决方案。不理想,但它有效。

首先,我在 XAML 中将 Window.WindowState 设置为“最小化”。这可以防止窗口在渲染时出现在屏幕上。然后我订阅了窗口的 ContentRendered 事件,并在处理程序中添加了以下代码:

this.WindowState = System.Windows.WindowState.Normal;
this.MaxWidth = MainContentPresenter.ActualWidth;
this.Height = MainContentPresenter.ActualHeight;

this.InvalidateVisual();

其中 MainContentPresenter 是窗口的 ContentPresenter。ViewModel 绑定到这个元素,所以内容出现在那里。

于 2011-03-14T20:43:22.460 回答
0

请注意,您可以知道窗口需要什么大小的事件,而根本不显示它。

如果您有一个控件想知道它想要的大小,您可以执行以下操作

// I'm picking Button here, but any control could be put here, be it
// Window or whatever:

Button b = new Button();

// I'm putting some content to see that it actually measures it children. If you'll put more text here
// you'll see bigger size
b.Content = "Hello";

// I'm manually measuring the control, passing in double.PositiveInfinity so that the control
// would give me the size it wants, regardless of any constraints (you can put constraints here
// if you like)
b.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));

// After Measure is called, the Property DesiredSize become relevant, and contains the size that the
// Control needs to show all of its contents.
MessageBox.Show(b.DesiredSize.ToString());
于 2011-03-14T23:06:47.620 回答
0

好的,我发现了我的错误。只要在显示窗口之前设置了新窗口的 DataContext,SizeToContent 设置为 WidthAndHeight 就可以正常工作。如:

secondaryWindow.DataContext = viewModel;  

secondaryWindow.Show();

而不是:

secondaryWindow.Show();

secondaryWindow.DataContext = viewModel;  

就像我一样。

所以发生的事情是,在 DataContext 为空的情况下,窗口的大小适当,然后在设置 DataContext 时重新调整大小。

感谢 Elad Katz 添加了一个间接导致我发现这个错误的解决方案。

于 2011-03-16T17:49:34.467 回答