我有一个两列的网格。我希望最左列的宽度是网格可用宽度的50%,或者是适合列中包含的任何控件所需的宽度,以较大者为准。我怎样才能做到这一点?有条件地设置网格列宽度
换句话说,我希望列的宽度尽可能小,但最小为50%。
我有一个两列的网格。我希望最左列的宽度是网格可用宽度的50%,或者是适合列中包含的任何控件所需的宽度,以较大者为准。我怎样才能做到这一点?有条件地设置网格列宽度
换句话说,我希望列的宽度尽可能小,但最小为50%。
理想情况下,你可以设置在ColumnDefintion
到0.5 MinWidth
财产*。但是,此属性预计Double
而不是GridLength
。
XAML:
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" MinWidth="{Binding ElementName=otherColumn, Path=ActualWidth, Converter={l:DivideByTwoConverter}}" />
<ColumnDefinition x:Name="otherColumn" />
</Grid.ColumnDefinitions>
<TextBox Grid.Column="0" />
<TextBox Grid.Column="1" />
</Grid>
转换:要解决这一点,你可以使用一个转换器采取强制方法
public class DivideByTwoConverter : MarkupExtension, IValueConverter
{
public override object ProvideValue(IServiceProvider serviceProvider)
{
return this;
}
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is double)
{
return (double) value/2;
}
return DependencyProperty.UnsetValue;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
在这个例子中,列开出的宽度的一半。当你输入文字到TextBox
并且它增长时,该列也会增长。
希望这会有所帮助!
如果父母的宽度是先验知道,那么这很容易。如果父母的宽度为100,则:
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" MinWidth="50" />
<ColumnDefinition Width="1*" />
</Grid.ColumnDefinitions>
</Grid>