gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 18:50:11 25 4
gpt4 key购买 nike

我有这个组合框

<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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com