我正在尝试在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
}
关于c# - 根据父级宽度绑定(bind)UniformGrid列,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18862193/