【发布时间】:2016-04-19 20:42:36
【问题描述】:
我正在开发 WPF GUI,我希望窗口根据内容自动调整大小,但不是所有内容:我有一些不同的按钮和其他控件,我想自动调整宽度。如果我在列表框中添加一个长项,我希望窗口保持相同的大小。
示例代码:
<Window x:Class="QuickieWPF.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" SizeToContent="WidthAndHeight" ResizeMode="CanMinimize">
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<StackPanel Orientation="Horizontal">
<Button Width="100" Content="Foo" Click="Button_Click"/>
<Button Width="100" Content="Bar" Click="Button_Click"/>
<Button Width="100" Content="Baz" Click="Button_Click"/>
</StackPanel>
<ListBox Grid.Row="1" Name="TheList" Height="100"/>
</Grid>
</Window>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
string str = "This is a really long text item that will be wider than the " +
"three buttons. I want a horizontal scrollbar on the listbox, not a wider " +
"window. I want the window to size to the buttons, not to this listbox.";
this.TheList.Items.Add(str);
}
}
最初,窗口大小调整为按钮:
在列表框中添加长项后,我目前得到这个:
但我宁愿得到这个:
(我通过在列表框上设置 MaxWidth 来制作最后一个屏幕截图,但这对于完整的应用程序来说不是一个好的解决方案:在完整的应用程序中,它不仅仅是三个按钮;它是按钮、图标、文本框、标签等,我希望窗口自动调整到整个混乱,而不是底部的列表框。)
【问题讨论】: