简体   繁体   English

设置 window 大小以适应内容,但阻止 window 宽度超出屏幕宽度

[英]Set window size to fit content, but stop the window width from going beyond screen width

I want to create a sort of a popup window like the Overloads window in Visual Studio.我想在 Visual Studio 中创建一种类似于重载 window的弹出窗口 window。 And just like the Overloads window, it can pop up pretty much anywhere on the screen.就像 Overloads window 一样,它几乎可以在屏幕上的任何位置弹出。

I have a Window that has a child TextBlock control.我有一个具有子TextBlock控件的Window The Window changes its size according to the TextBlock size by setting its SizeToContent property to WidthAndHeight . Window通过将其SizeToContent属性设置为WidthAndHeight来根据TextBlock大小更改其大小。 If the TextBlock Text is too long, the Window resizes its width beyond the screen's width resulting in a partially visible Window .如果TextBlock Text太长,则Window调整其宽度超出屏幕宽度,从而导致部分可见Window I would like the Text to wrap when it reaches the end of the screen, so to say.我希望Text在到达屏幕末尾时换行,可以这么说。

I tried setting the TextBlock TextWrapping property to Wrap to hopefully stop this behavior, but it doesn't help because of the SizeToContent property being set.我尝试将TextBlock TextWrapping属性设置为Wrap以希望阻止这种行为,但由于设置了SizeToContent属性,它没有帮助。 Any suggestions/workarounds?有什么建议/解决方法吗?

Thanks for your help!谢谢你的帮助!

You could set the MaxWidth property of the window to the width of the screen, eg:您可以将 window 的MaxWidth属性设置为屏幕的宽度,例如:

TextBlock text = new TextBlock()
{
    Text = "some very long string...",
    TextWrapping = TextWrapping.Wrap
};
Window window = new Window()
{
    SizeToContent = SizeToContent.WidthAndHeight,
    Content = text,
    MaxWidth = System.Windows.SystemParameters.PrimaryScreenWidth
};
window.Show();

How to get the size of the current screen in WPF? 如何在WPF中获取当前屏幕的大小?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM