根据父宽度绑定统一网格列

本文关键字:网格 绑定 | 更新日期: 2023-09-27 18:31:47

我正在尝试绑定 ItemsControl 中的 UniformGrid Columns 属性。

到目前为止,我有:

<ScrollViewer x:Name="scroll" VerticalScrollBarVisibility="Auto">
    <ItemsControl ItemsSource="{Binding}" >
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <UniformGrid>
                    <UniformGrid.Columns>
                        <MultiBinding Converter="{StaticResource Columns}">
                            <Binding RelativeSource="{RelativeSource Self}" />
                            <Binding Source="{x:Reference scroll}" />
                        </MultiBinding>
                    </UniformGrid.Columns>
                </UniformGrid>
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
    </ItemsControl>
</ScrollViewer>

在转换器中:

const double TileWidth = 154;
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
    double width, aWidth;
    UniformGrid grid = values[0] as UniformGrid;
    ScrollViewer scroll = values[1] as ScrollViewer;
    var gw = grid.Width;
    var gaw = grid.ActualWidth;
    aWidth = scroll.ActualWidth;
    width = aWidth - (scroll.Padding.Left + scroll.Padding.Right);
    return 3;
    // return width / TileWidth;
}

我无法获得父控件的任何宽度来确定要显示的列数。 他们要么0.0,要么NaN.

如何获取父母的宽度以确定有多少可用空间?

根据父宽度绑定统一网格列

使用 UniformGrid,尝试创建一个变量 cols 并绑定它

 <UniformGrid Columns="{Binding ElementName=_this, Path=TileColumns}"> 

然后在代码隐藏中,计算所需的列数,检查 ActualWidth 并设置该变量。

public int TileColumns
{
    get { return (int)GetValue(TileColumnsProperty); }
    set { SetValue(TileColumnsProperty, value); }
}
// Using a DependencyProperty as the backing store for TileColumns.  This enables animation, styling, binding, etc...
public static readonly DependencyProperty TileColumnsProperty =
    DependencyProperty.Register("TileColumns", typeof(int), typeof(TileView), new PropertyMetadata(3));
private void scroll_SizeChanged(object sender, SizeChangedEventArgs e)
{
    var aw = scroll.ActualWidth;
    TileColumns = (int)aw / 154; // 154 is a Tile's width
}