未处理前效果:
处理后效果:
<Border Background="{StaticResource BorderBg}" BorderThickness="2" BorderBrush="{StaticResource BorderBrush}" CornerRadius="5" Padding="5" x:Name="SvKeyWords" Margin="142,0,134,58" Height="175" VerticalAlignment="Bottom" Visibility="Collapsed" Opacity="0.98"><ScrollViewer VerticalScrollBarVisibility="Auto" ><WrapPanel x:Name="WpKeyWords"/></ScrollViewer></Border>
private void AlignWrapPanelChild(){//WrapPanel 所有子元素var lst = (from object child in WpKeyWords.Children select child as Border).ToList();if (lst.Count > 1){//每次 重置 子元素宽度foreach (var t in lst){t.Width = double.NaN;t.UpdateLayout();}for (var i = 0; i < lst.Count - 1; i++){//找到每行最后一个子元素var child = lst[i];var nxtChild = lst[i + 1];var plWidth = WpKeyWords.ActualWidth;var childPoint = child.TranslatePoint(new Point(0, 0), WpKeyWords);var nxtChildPoint = nxtChild.TranslatePoint(new Point(0, 0), WpKeyWords);if (nxtChildPoint.X < childPoint.X){//找出同一行的子元素var tempLst = lst.Where(b => b.TranslatePoint(new Point(0, 0), WpKeyWords).Y.Equals(childPoint.Y)).ToList();//算出多余的空白宽度var surplusWidth = plWidth - childPoint.X - child.Margin.Right - child.ActualWidth;var averageAddWidth = surplusWidth / tempLst.Count;//将多余的宽度平均分给当前行每个子元素foreach (var b in tempLst){b.Width = b.ActualWidth + averageAddWidth;b.UpdateLayout();}}}}}
在数据绑定或者初始化控件后调用
private void do()
{……WpKeyWords.SizeChanged += delegate { AlignWrapPanelChild(); };AlignWrapPanelChild();
}