必要なものを確保するグリッドコントロールの依存関係プロパティ (例: と呼ばれるHorizontalPropFillOfBlankSpace
) を作成できます(列は Width="*" ですが、内容に合わせて MinWidth を指定します)。次に、必要なグリッドに適用できます。
<Grid namespace:GridHelper.HorizontalPropFillOfBlankSpace="True">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
...
この依存関係プロパティの実装例を以下に示します。Width="Auto"
ギャップ スペースを埋めるために自動的にサイズ変更されるのは、の列のみです。必要なものをカスタマイズできます。
public class GridHelper
{
/// <summary>
/// Columns are resized to proportionally fill horizontal blank space.
/// It is applied only on columns with the Width property set to "Auto".
/// Minimum width of columns is defined by their content.
/// </summary>
public static readonly DependencyProperty HorizontalPropFillOfBlankSpaceProperty =
DependencyProperty.RegisterAttached("HorizontalPropFillOfBlankSpace", typeof(bool), typeof(GridHelper), new UIPropertyMetadata(false, OnHorizontalPropFillChanged));
public static bool GetHorizontalPropFillOfBlankSpace(Grid grid)
=> (bool)grid.GetValue(HorizontalPropFillOfBlankSpaceProperty);
public static void SetHorizontalPropFillOfBlankSpace(Grid grid, bool value)
=> grid.SetValue(HorizontalPropFillOfBlankSpaceProperty, value);
private static void OnHorizontalPropFillChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (!(d is Grid grid))
return;
if ((bool)e.NewValue)
{
grid.Loaded += Grid_Loaded;
}
else
{
grid.Loaded -= Grid_Loaded;
}
}
private static void Grid_Loaded(object sender, RoutedEventArgs e)
{
if (!(sender is Grid grid))
return;
foreach (var cd in grid.ColumnDefinitions)
{
if (cd.Width.IsAuto && cd.ActualWidth != 0d)
{
if (cd.MinWidth == 0d)
cd.MinWidth = cd.ActualWidth;
cd.Width = new GridLength(1d, GridUnitType.Star);
}
}
}
}