這裏是一個包含UserControl
的WPF窗口。 UserControl
是一個簡單的Grid
,其中2列沒有明確的寬度。在第一列中,我添加了一個簡單的TextBox
設置爲水平拉伸。第二列是空的。當ColumnDefinitions的寬度是動態的時,WPF會創建不需要的邊距?
由於我縮小了窗口的寬度,WPF在我的UserControl
中裁剪,即使其右側仍有一個巨大的空白區域!它看起來像試圖讓我的第二列與我的第一列相同,即使它是空的,但奇怪的是,這發生在我的UserControl之外(否則空白將是粉紅色!)...
MainWindow .XAML:
<Window x:Class="WPF_Grid_Test.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WPF_Grid_Test"
Title="MainWindow" Height="350" Width="525">
<local:TestUserControl HorizontalAlignment="Left"/>
</Window>
UserControl.XAML:
<UserControl x:Class="WPF_Grid_Test.TestUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Background="Pink" Height="100">
<Grid Margin="0" ShowGridLines="True">
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<TextBox Text="Why is WPF cropping me even though there's a huge blank space to eat into?" VerticalAlignment="Center" />
</Grid>
</UserControl>
我試圖將所有Margins
和Paddings
爲0,沒有變化。
當UserControl
被設置爲水平居中(而不是左)時,的行爲更加怪異!而不是在右側創建一個巨大的保證金,保證金實際上均勻分佈在左側和右側。我希望我的UserControl
的動態調整大小隻有在WPF用完所有可用空間後纔會發生。這不是什麼程序員會期望的?
(我真正的項目實際上有3列,分別包含一個TextBlock,一個文本框和按鈕,但行爲是一樣的:WPF吃進了自己的自動生成量之前的UI元素將被裁剪)
當我在列(即,或「自動」)上設置明確的寬度時,WPF將在裁剪我的UserControl之前正確擺脫其空白空間。但是這可以防止WPF在窗口變得更薄時縮小UserControl。
所以我的第一個問題是,是不是這是一個WPF錯誤?
我的第二個問題,如何設置列,以便僅WPF開始調整我的用戶,一旦它真的出的空間來顯示呢?
這是.NET 4.0。存在一個類似的問題here但我不太瞭解解決方案。
更新: 這是UserControl
的另一個示例代碼。當設置列寬爲「自動」的建議,該UserControl
將停止爲窗口收縮縮小它的元素,並最終將裁剪最右邊的元素,一旦空間實在是欠缺:
<UserControl x:Class="WPF_Grid_Test.TestUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Background="Pink" Height="100">
<Grid Margin="0" ShowGridLines="True">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<TextBox Text="Resize us" VerticalAlignment="Center" Grid.Column="0" />
<TextBox Text="only when" VerticalAlignment="Center" Grid.Column="1" />
<TextBox Text="you're out of space!" VerticalAlignment="Center" Grid.Column="2" />
</Grid>
</UserControl>
行爲我想要實現的是UserControl
在縮小窗口時保留其DesiredSize
。但只有當窗口空出時,應該收到UserControl
的「縮小」處理。
嘗試從ColumnDefinitions中刪除Width=Auto
,您應該看到在容器缺少空間之前如何調整之前最右邊的元素。這就是爲什麼我認爲這確實是一個WPF佈局錯誤。
設置這些會根據其內容給UserControl一個固定的寬度,這不是我正在尋找的行爲。用戶自定義大小並在空間不足時修剪其元素,我沒有問題。如果你嘗試了上面的代碼,你會注意到即使Container * does *有足夠的空間來顯示它,UserControl也會被縮小。 – Joe
我已經用你的想法更新了我的初始文章,並解釋了它如何不提供預期的行爲。 – Joe