我有一个DockPanel,我以编程方式添加TextBlock控件. DockPanel定义如下:
<DockPanel x:Name="staHeadlines" Margin="0,10,0" ScrollViewer.VerticalScrollBarVisibility="disabled"/>
TextBlocks添加到DockPanel,如下所示:
For count = headlinePosition To maxHeadlineCount Dim tb As New TextBlock With {.Text = headlines.Item(count),.FontFamily = New FontFamily("Segoe UI Semilight"),.FontSize = "22",.textwrapping = textwrapping.Wrap,.Margin = New Thickness(0,10)} DockPanel.SetDock(tb,Dock.Top) staHeadlines.Children.Add(tb) Next
DockPanel用于显示新闻标题,每个TextBlock一个.我想添加足够的TextBlock来填充可用空间,但不要让底部项溢出DockPanel边界.由于TextBlock的高度是由内容定义的 – 我事先并不知道 – 我需要能够计算添加到DockPanel的所有项目的高度,以确定添加的最后一个子项是否会溢出DockPanel的边界并出现剪裁.
有任何想法吗?
解决方法
你可以试试这样的……
private void TryAddNewTextBox(TextBox textBox) { this.staHeadlines.Children.Add(textBox); textBox.Measure(new Size(double.PositiveInfinity,double.PositiveInfinity)); var totalChildrenHeight = textBox.DesiredSize.Height + this.staHeadlines.Children.OfType<TextBox>().Sum(childTextBox => GetElementBoundsHeight(childTextBox)); if (totalChildrenHeight > GetElementBoundsHeight(this.staHeadlines)) this.staHeadlines.Children.RemoveAt(this.staHeadlines.Children.Count - 1); } private double GetElementBoundsHeight(FrameworkElement element) { return element.RenderTransform.TransformBounds(new Rect(element.RenderSize)).Height; }
这里棘手的部分是在渲染之前获取新TextBox的大小.我们首先添加到DockPanel,然后在TextBox上调用Measure.通过传递新的大小(double.PositiveInfinity,double.PositiveInfinity),我们基本上说’先生TextBox,让您自己尽可能大地展示您的内容.通过这样做,我们知道新控件的大小.然后我们要做的就是将新TextBox的高度添加到所有DockPanel的子高度范围的总和.将其结果与DockPanel和BOOM的边界进行比较.可以清理一下这段代码,但希望它有所帮助.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。