本文來自翻譯(谷歌翻譯加持)。
原文作者: eric ouellet
原文標題:wpf - wrappanel with fill
原文連結:https://www.codeproject.com/Tips/990854/WPF-WrapPanel-with-Fill
原文示例代碼:https://www.codeproject.com/KB/static/990854/WpfWrapPanelWithFill.zip
居間
我意识到很多人都需要和我一样的布局容器:一个 WrapPanel,可以用一个或多个子控件填充右边空白空间(Orientation=Horizontal,站长注:注意了哦,不一定填充的是在最左边,也不一定是最右边,可以是中间哦)。我决定编写一个可重复使用的控件来在两个方向上完成这项工作。
該代碼包含一個小演示,您可以在其中輕鬆查看它是否符合您的需要。
注意:我非常感謝反饋。如果您不喜歡代碼,請告訴我原因。我希望它可以幫助任何人。
示例代碼截圖

背景
stackoverflow 上有幾個問答,但沒有真正簡單的解決方案可以在多行時起作用。另外,我想做一個可以在任何地方輕鬆重複使用的控制項(容器)。我從微軟的代碼開始修改它以提供所需的行為。
使用代碼
您可以使用 dll 或僅將原始碼(只有一個.cs 文件)複製到您自己的庫中。
用法如下:
<Window x:Class="WpfWrapPanelWithFillTestApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:wrapPanelWithFill="clr-namespace:WrapPanelWithFill;assembly=WrapPanelWithFill"
Title="MainWindow" Height="400" Width="800">
<wrapPanelWithFill:WrapPanelFill Grid.Row="2" Grid.Column="6" Orientation="Vertical">
<TextBlock Text="Path: " TextWrapping="Wrap"></TextBlock>
<TextBox MinWidth="120" wrapPanelWithFill:WrapPanelFill.UseToFill="True">*</TextBox>
<Button>Browse...</Button>
</wrapPanelWithFill:WrapPanelFill>
</Window>
限制(改進方法)
- 为定义为填充的控件考虑设置
MaxWidth属性(或当Orientation是Vertical时设置MaxHeight)。 - 每個子控制項的填充寬度始終相同(當更多子控制項被定義為“填充”時。如果在“grid”中使用“gridlength”做相同的“比例”定義會很好。例如 rowdefinition 的“width”)。
- 添加
HorizontalContentAlignement和VerticalContentAlignement使控件更加完整。 当我们需要在右侧或中心而不是左侧对齐控件时,它很有用。 我在 StackOverflow 的 DTig 找到了一个很好的解决方案。
理想情況下,它是一個解決方案中每項改進的組合,這將是很好的。
歷史
- 2015-05-12, 第一版
- 2015-05-13,使代碼更簡潔,修復了提示中的一些錯誤並添加了屏幕截圖
- 2015-05-22,澄清限制。稍微改進一下文本。
協議
本文以及任何相關的原始碼和文件均已獲得代碼項目開放許可證 (cpol) 的許可
站長追加
本文功能最佳食用效果如前面說的,把容器代碼複製到自己的項目中,然後使用。
站长也将该容器添加到Dotnet9WPFCotnrols包下,代码如下:
<Window
/**省略 */
xmlns:dotnet9="https://dotnet9.com"
/**省略 */
>
/**省略 */
<GroupBox Header="WrapPanelFill">
<StackPanel Orientation="Vertical">
<Image
Width="300"
Height="300"
Source="Images/Swift.png" />
<dotnet9:WrapPanelFill>
<Button Content="反馈" Style="{StaticResource Styles.ButtonDemo}" />
<TextBlock dotnet9:WrapPanelFill.UseToFill="True" />
<Button Content="喜欢" Style="{StaticResource Styles.ButtonDemo}" />
<Button Content="不感冒" Style="{StaticResource Styles.ButtonDemo}" />
</dotnet9:WrapPanelFill>
</StackPanel>
</GroupBox>
</Window>
和前面的代码类似,使用一个TextBlock作为空白填充,运行效果如下:

最後再給出本文所有代碼出處:
- 原文示例代碼:https://www.codeproject.com/KB/static/990854/WpfWrapPanelWithFill.zip
- dotnet9wpfcontrols 包:https://www.nuget.org/packages/Dotnet9WPFControls/0.1.0-preview.3
- dotnet9wpfcontrols 源碼:https://github.com/dotnet9/Dotnet9WPFControls
- 文末示例代碼:https://github.com/dotnet9/TerminalMACS.ManagerForWPF/blob/master/src/Demo/WpfThemeDemo/MainWindow.xaml