gpt4 book ai didi

c# - 水平对齐包裹面板中的子元素

转载 作者:行者123 更新时间:2023-11-30 12:25:12 25 4
gpt4 key购买 nike

我的窗口中有以下 XAML:

<WrapPanel>
<WrapPanel.Resources>
<Style TargetType="Rectangle">
<Setter Property="Margin" Value="10,10,10,10"/>
<Setter Property="VerticalAlignment" Value="Top"/>
</Style>
</WrapPanel.Resources>
<Rectangle Height="100" Width="100" Fill="Red"/>
<Rectangle Height="200" Width="200" Fill="Yellow"/>
<Rectangle Height="150" Width="150" Fill="Green"/>
<Rectangle Height="50" Width="50" Fill="Blue"/>
<Rectangle Height="250" Width="250" Fill="Purple"/>
</WrapPanel>

在设计器中生成以下 UI: Current layout

我正在寻找的是一种“水平对齐”包裹面板中子元素的方法,这样窗口看起来就像这样: Desired layout

有什么方法可以在包装面板中实现这一点,还是我需要考虑使用其他控件或编写自定义控件?

这张图片还说明了我正在努力实现的目标: enter image description here

最佳答案

使用几种不同的技术,您也许能够到达您想去的地方。这SO answer显示如何定义响应式列宽:

<Grid.ColumnDefinitions>
<ColumnDefinition Width="3*"/>
<ColumnDefinition Width="2*"/>
<ColumnDefinition Width="3*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="3*"/>
<RowDefinition Height="2*"/>
<RowDefinition Height="3*"/>
</Grid.RowDefinitions>

如果这还不够,您可以沿着使用网格布局的自定义控件的路径前进,并重新定位每个子控件当前所在的列/行,并在控件或窗口调整大小事件中重做基于列/像素计算的布局定位。

更新:

对于自定义控件,您可以尝试类似的操作:

公共(public)类 CustomLayout : 控件 { 私有(private)列表子项;

  public CustomLayout()
{
children = new List<Control>();
}

public void AddChild(Control childToAdd)
{
children.Add(childToAdd);
// TODO: Determine if new layout is needed.
}

public void RemoveChild(Control childToRemove)
{
children.Remove(childToRemove);
// TODO: Determine if new layout is needed.
}

// Call to update the layout.
private void PerformLayout(int columns, int rows)
{
Grid layoutGrid = new Grid();
// TODO: Programmatically build grid layout.
RowDefinition row = new RowDefinition();
row.Height = 100;
layoutGrid.Rows.Add(row);

// Methods for layout:
// Grid.SetRow(rowID, childControl);
// Grid.SetColumn(columnID, childControl);


// Note: This may produce some flashing on resize, so there may be better ways to remove/add the grid such as redoing rows and columns instead.
Controls.Clear();
Controls.Add(layoutGrid);
}

// Should be called when the window or parent resizes. I can't remember the events in question.
public void OnResize()
{
int columns;
int rows;
// TODO: Calculate columns/rows
PerformLayout(columns, rows);
}

希望这能让您朝着正确的方向前进。请记住,这是伪代码,可能无法完全编译。

关于c# - 水平对齐包裹面板中的子元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31950518/

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