根据父Width绑定UniformGrid列

时间:2013-09-18 00:53:51

标签: c# wpf xaml

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

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

1 个答案:

答案 0 :(得分: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
}