Dot-Net
為什麼帶有 * 的 WPF 網格中的兩列大小不同?
使用下面的程式碼,我希望以兩個具有相同寬度的 ListBox 結束,它們進入兩個帶有 With="*" 的 columndefinition
相反,看起來大小是由 ListBox 上的文本大小確定的,這是沒有意義的,因為該文本比 ListBox 小得多,因此 TextBlock 有足夠的空間來容納文本。
<Window x:Class="UnderstandSizing.Window5" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window5" SizeToContent="WidthAndHeight" ResizeMode="NoResize" > <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="*" /> <ColumnDefinition Width="Auto" /> <ColumnDefinition Width="*" /> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> </Grid.RowDefinitions> <TextBlock Text="Text1longer" Grid.Row="0" Grid.Column="0" x:Name="Test1" /> <TextBlock Text="Text1" Grid.Row="0" Grid.Column="2" /> <ListBox Grid.Row="1" Grid.Column="0" Height="150" /> <ListBox Grid.Row="1" Grid.Column="2" Height="150" /> <TextBlock Grid.Row="2" Grid.ColumnSpan="3" Text="This textblock sets the max width" Width="300" /> </Grid> </Window>
WPF 自動調整大小功能讓我抓狂……有什麼想法嗎?謝謝。
編輯:一切都在 VS2008 中完成,以防萬一。
亞歷克斯。A 找到了正在發生的事情的確切原因,我在一次幸運的罷工中找到了解決方案。只需將 * 更改為 0 我得到預期的結果(如果你問我很奇怪):
<Window x:Class="UnderstandSizing.Window5" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window5" SizeToContent="WidthAndHeight" ResizeMode="NoResize" > <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="0" /> <ColumnDefinition Width="Auto" /> <ColumnDefinition Width="0" /> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> </Grid.RowDefinitions> <TextBlock Text="Text1longer" Grid.Row="0" Grid.Column="0" x:Name="Test1" /> <TextBlock Text="Text1" Grid.Row="0" Grid.Column="2" /> <ListBox Grid.Row="1" Grid.Column="0" Height="150" /> <ListBox Grid.Row="1" Grid.Column="2" Height="150" /> <TextBlock Grid.Row="2" Grid.ColumnSpan="3" Text="This textblock sets the max width" Width="300" /> </Grid> </Window>
看這個:
http://www.wpftutorial.net/GridLayout.html
“星星 (*):
佔用盡可能多的空間(在填充所有自動和固定大小的列之後),按比例分配給所有星形大小的列。所以 3*/5* 和 30*/50* 的意思是一樣的。請記住,如果網格大小是根據其內容計算的,則星號大小不起作用。"
您的程式碼就是這種情況。我懷疑這也是其他人測試它看起來不錯的原因,如果他們將網格粘貼到一個大於 TextBlock 設置的 300 像素的視窗中。如果我使用完全相同的 XAML,我會遇到同樣的問題。
**編輯:**這就是“為什麼”。有關可能的替代解決方案,請參閱此問題:Wpf: Grid: How can i share column/row height width?
在這種情況下,最新的答案(不是提問者選擇的答案)似乎是最有用的答案。
