【发布时间】:2009-06-23 19:02:39
【问题描述】:
我知道如何在代码中做到这一点,但这可以在 XAML 中完成吗?
Window1.xaml:
<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Grid>
<ComboBox Name="ComboBox1" HorizontalAlignment="Left" VerticalAlignment="Top">
<ComboBoxItem>ComboBoxItem1</ComboBoxItem>
<ComboBoxItem>ComboBoxItem2</ComboBoxItem>
</ComboBox>
</Grid>
</Window>
Window1.xaml.cs:
using System.Windows;
using System.Windows.Controls;
namespace WpfApplication1
{
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
double width = 0;
foreach (ComboBoxItem item in ComboBox1.Items)
{
item.Measure(new Size(
double.PositiveInfinity, double.PositiveInfinity));
if (item.DesiredSize.Width > width)
width = item.DesiredSize.Width;
}
ComboBox1.Measure(new Size(
double.PositiveInfinity, double.PositiveInfinity));
ComboBox1.Width = ComboBox1.DesiredSize.Width + width;
}
}
}
【问题讨论】:
-
查看stackoverflow.com/questions/826985/… 上类似行的另一篇帖子如果回答了您的问题,请将您的问题标记为“已回答”。
-
我也在代码中尝试过这种方法,但发现在 Vista 和 XP 之间测量值可能会有所不同。在 Vista 上,DesiredSize 通常包括下拉箭头的大小,但在 XP 上,宽度通常不包括下拉箭头。现在,我的结果可能是因为我试图在父窗口可见之前进行测量。在 Measure 之前添加 UpdateLayout() 会有所帮助,但可能会导致应用程序中的其他副作用。如果您愿意分享,我很想看看您提出的解决方案。
-
您是如何解决问题的?