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

标签 .net wpf combobox

我有这个组合框

<ComboBox ItemsSource="{Binding Path=Foo.Bars}"/>

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

例如,如果内容是:
John Doe
Jane Mary
Josh

长度将等于简玛丽的长度。

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

最佳答案

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

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();
    }
}

然后通过将列表作为路径绑定(bind)并将转换器作为值转换器来简单地绑定(bind) 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}}"/>

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

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

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

关于.net - 如何将组合框大小设置为其内容的最大宽度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7399405/

相关文章:

c# - App.config 文件版本与应用程序?

c# - 以编程方式从 .NET Webbrowser Control 的下拉列表中选择一个项目

.net - 有没有好的 WPF 图表制作者/工具包/提供者?

c# - 绑定(bind)到 MainView 窗口的 Width 属性时出现绑定(bind)错误

c# - ComboBox.SelectedValue 不工作

c# - MVVM Caliburn.micro 组合框 Country-City 无法正常工作

c# - WPF Magellan ViewModel IOC

.NET Core 1.1 资源文件问题

wpf - 如何使 ListBoxItem 垂直拉伸(stretch)

wpf - 如何自定义通用异常消息 "Value ' ' 无法转换“