如何将组合框大小设置为其内容的最大宽度?

Lou*_*hys 5 .net wpf combobox

我有这个ComboBox

<ComboBox ItemsSource="{Binding Path=Foo.Bars}"/>
Run Code Online (Sandbox Code Playgroud)

我可以将组合框的大小设置为其最宽项目的宽度吗?

例如,如果内容是:

John Doe
Jane Mary
Josh
Run Code Online (Sandbox Code Playgroud)

长度将等于Jane Mary的长度.

此外,在这种情况下,预计在初始化之后内容不会改变

Uco*_*dia 3

您可以做的是创建一个转换器,该转换器将返回对象属性的最长长度。您可以像这样实现转换器:

public class LongestListObjectToIntConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value is IEnumerable<FooBar>)
        {
            IEnumerable<FooBar> list = (IEnumerable<FooBar>)value;

            return list.Max(bar => bar.FullName.Length);
        }

        // Default value to return
        return 100;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}
Run Code Online (Sandbox Code Playgroud)

然后通过提供列表作为路径绑定以及提供转换器作为值转换器来简单地绑定 ComboBox 的 Width 属性。

<Window.Resources>
    <conv:LongestListObjectToIntConverter x:Key=converter/>
</Windows.Resources>

    ...

<ComboBox ItemsSource="{Binding Path=Foo.Bars}" Width="{Binding Path=Foo.Bars, Converter={StaticResource converter}}"/>
Run Code Online (Sandbox Code Playgroud)

这样,即使您的集合发生更改并且未通知此更改,组合框也会根据最长的单词调整大小。

另一个有趣的想法是在宽度上进行自绑定并抓取转换器中的实际组合框,然后检查显示的值,我认为这会更好。

该解决方案的优点是不使用隐藏代码并且易于重用。您可以在这里找到有关 ValueConverters 的更多信息:http://www.wpftutorial.net/ValueConverters.html