我有一个组合框:
<ComboBox Grid.Row="1" HorizontalAlignment="Center" VerticalAlignment="Center"
ItemsSource="{Binding Options}"
SelectedItem="{Binding SelectedOption}"
DisplayMemberPath="DisplayName"/>
Options 中的第一项将始终包含一个选项,其中 option.DisplayName = string.Empty 这会导致组合框非常薄,因为不需要空间来显示 string.Empty。
在 XAML 中,有没有办法自动将 ComboBox 的宽度设置为 ItemsSource 中最大字符串的大小?我不想测量最长项目的宽度并将其设置在 .xaml.cs
如果重要的话,组合框所在的网格看起来像:
<Grid Margin="5" Height="500">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
如果您希望将
ComboBox
在布局中居中,但仍希望其自动调整大小,则可以使用 Grid
作为布局容器。这样Grid
就会照顾好你的ComboBox
。
由于您已经在使用
Grid
来布局元素,因此您所要做的就是定义列。
只需创建至少三列(您可以使用
Grid.ColumnSpan
将列合并为居中元素的三列行)并将 ComboBox
放置在中心列中。在其他元素上设置 Grid.ColumnSpan
,以允许它们跨越整个 Grid
。然后将 HorizontalAlignment
的 ComboBox
设置回 HorizontalAlignment.Stretch
(这是默认值):
<Grid Margin="5" Height="500">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition /> <!-- Center column -->
<ColumnDefinition />
</Grid.ColumnDefinitions>
<!-- The centered ComboBox element -->
<ComboBox Grid.Row="1"
Grid.Column="1" />
<!-- A TextBox element that stretches across the full Grid -->
<TextBox Grid.Row="2"
Grid.Column="0"
Grid.ColumnSpan="3" />
</Grid>