2

我正在尝试在 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

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

4

1 回答 1

3

使用 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
}
于 2013-09-18T01:41:50.127 回答