gpt4 book ai didi

wpf - 我们如何为 WrapPanel 设置 Wrap-point?

转载 作者:行者123 更新时间:2023-12-04 23:52:14 27 4
gpt4 key购买 nike

我有一个 ItemsControl,我希望将数据输入到两列中。当用户调整到小于第二列的宽度时,第二列的项目必须换行到第一列。类似于 UniformGrid 但带有包装。

我已经设法使用 WrapPanel 来做到这一点。但是我被迫操纵和硬编码 WrapPanel 的 ItemWidth 和 MaxWidth 来实现两列的东西和包装。这不是一个好的做法。

是否可以设置最大列数,或者换句话说,允许我们决定 WrapPanel 应该在什么时候开始换行?

网上的一些浏览显示,Windows 8 Metro 中的 WrapGrid 有这个 property .有没有人在 WPF 中有这个实现?

最佳答案

有一个 UniformWrapPanel codeproject.com 上的文章,我对其进行了修改以确保包装面板中的项目具有统一的宽度并适合窗口的宽度。您应该能够轻松地修改此代码以具有最大列数。尝试更改附近的代码

var itemsPerRow = (int) (totalWidth/ItemWidth);

为了指定最大列。

代码如下:

public enum ItemSize
{
None,
Uniform,
UniformStretchToFit
}

public class UniformWrapPanel : WrapPanel
{
public static readonly DependencyProperty ItemSizeProperty =
DependencyProperty.Register(
"ItemSize",
typeof (ItemSize),
typeof (UniformWrapPanel),
new FrameworkPropertyMetadata(
default(ItemSize),
FrameworkPropertyMetadataOptions.AffectsMeasure,
ItemSizeChanged));

private static void ItemSizeChanged(
DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
var uniformWrapPanel = sender as UniformWrapPanel;
if (uniformWrapPanel != null)
{
if (uniformWrapPanel.Orientation == Orientation.Horizontal)
{
uniformWrapPanel.ItemWidth = double.NaN;
}
else
{
uniformWrapPanel.ItemHeight = double.NaN;
}
}
}

public ItemSize ItemSize
{
get { return (ItemSize) GetValue(ItemSizeProperty); }
set { SetValue(ItemSizeProperty, value); }
}

protected override Size MeasureOverride(Size availableSize)
{
var mode = ItemSize;

if (Children.Count > 0 && mode != ItemSize.None)
{
bool stretchToFit = mode == ItemSize.UniformStretchToFit;

if (Orientation == Orientation.Horizontal)
{
double totalWidth = availableSize.Width;

ItemWidth = 0.0;
foreach (UIElement el in Children)
{
el.Measure(availableSize);
Size next = el.DesiredSize;
if (!(Double.IsInfinity(next.Width) || Double.IsNaN(next.Width)))
{
ItemWidth = Math.Max(next.Width, ItemWidth);
}
}

if (stretchToFit)
{
if (!double.IsNaN(ItemWidth) && !double.IsInfinity(ItemWidth) && ItemWidth > 0)
{
var itemsPerRow = (int) (totalWidth/ItemWidth);
if (itemsPerRow > 0)
{
ItemWidth = totalWidth/itemsPerRow;
}
}
}
}
else
{
double totalHeight = availableSize.Height;

ItemHeight = 0.0;
foreach (UIElement el in Children)
{
el.Measure(availableSize);
Size next = el.DesiredSize;
if (!(Double.IsInfinity(next.Height) || Double.IsNaN(next.Height)))
{
ItemHeight = Math.Max(next.Height, ItemHeight);
}
}

if (stretchToFit)
{
if (!double.IsNaN(ItemHeight) && !double.IsInfinity(ItemHeight) && ItemHeight > 0)
{
var itemsPerColumn = (int) (totalHeight/ItemHeight);
if (itemsPerColumn > 0)
{
ItemHeight = totalHeight/itemsPerColumn;
}
}
}
}
}

return base.MeasureOverride(availableSize);
}
}

关于wpf - 我们如何为 WrapPanel 设置 Wrap-point?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9769618/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com