【发布时间】:2018-12-21 07:03:49
【问题描述】:
我正在制作一个 WPF 聊天程序,我想要显示消息的方式是这样的 (screenshot of how I have it now):
Sent Message
Received Message
Sent message2
Received Message
我在做什么:
一个滚动查看器,其中一个网格内部和网格内部 2 个堆栈面板,一个用于左侧,一个用于右侧。
<ScrollViewer x:Name="scrlViewer" VerticalScrollBarVisibility="Hidden" Width="472" Margin="10,10,0,67"
HorizontalAlignment="Left" Grid.ColumnSpan="2">
<Grid x:Name="ScrollViewerChild">
<StackPanel x:Name="ChatRow1" Width="200" Margin="10,10,0,10" HorizontalAlignment="Left" />
<StackPanel x:Name="ChatRow2" Width="200" Margin="0,10,10,10" HorizontalAlignment="Right"/>
</Grid>
</ScrollViewer>
然后在添加消息时我制作一个边框,然后制作一个 TextBlock。然后我将文本块添加到边框,然后将边框添加到相应的堆栈面板。
然后我尝试获取 TextBlock(或边框,两者都发生同样的事情)的高度,并制作 2 个不透明度为 0 的分隔符。将高度 10 添加到添加消息的面板中的高度之一,以及将 textBlockHeight + 10 添加到未添加任何内容的面板中的高度之一。
public void PrintOwnMessage(string msg)
{
var border = new Border()
{
Margin = new Thickness(0),
Padding = new Thickness(10,0,0,0),
BorderThickness = new Thickness(1),
BorderBrush = Brushes.White,
Background = Brushes.Azure,
CornerRadius = new CornerRadius(5)
};
var textBlock = new TextBlock()
{
Text = msg,
FontSize = 20,
TextWrapping = TextWrapping.Wrap
};
Console.WriteLine(border.DesiredSize);
border.Child = textBlock;
//panel[0] is the rightside panel where this function adds the message to
panel[0].Children.Add(border);
msgHeight = textBlock.ActualHeight;
textBlock.Measure(new Size(Double.PositiveInfinity, Double.PositiveInfinity));
var desiredSizeNew = textBlock.DesiredSize;
msgHeight = desiredSizeNew.Height + 10;
panel[0].Children.Add(new Separator() { Opacity = 0, Height = 10});
panel[1].Children.Add(new Separator() { Opacity = 0, Height = msgHeight });
scrl.ScrollToEnd();
}
问题:
“desiredSizeNew”变量似乎每次都是一样的。请注意,我以这种方式获取大小是因为尝试获取 .Height 会给我一个 NaN 而 .ActualHeight 总是返回零。
即使消息换成多行,它也总是给我一行的大小(“26.6”),所以只要消息只有 1 行的高度,代码就可以工作。
任何帮助将不胜感激! 我希望我能够很好地解释我的问题。这是我第一次用 c# 做任何东西,所以任何关于实现我想要的更好方法的建议都会很棒。虽然我想知道如何先解决这个问题。
【问题讨论】: