c# - 想要在网格中动态追加文本块 Wpf C#
问题描述
我想创建聊天机器人并使用响应网格作为主要聊天区域。每当我使用具有不同字符串的方法时,每次我的方法都会覆盖前一个文本块,但我想将下一个文本块附加到第一个文本块下方,如 whatsapp 和任何其他信使。
那是我的 xaml 代码
<Grid x:Name="Responce" HorizontalAlignment="Left" Height="315" VerticalAlignment="Top" Width="422" Margin="10,10,0,0"/>
那是我的 c# 方法,它创建文本块并将其添加到网格中。
private void CustomerReply(string sms)
{
StackPanel sp = new StackPanel();
var textBlock = new TextBlock();
var bc = new BrushConverter();
textBlock.Text = sms;
textBlock.HorizontalAlignment = HorizontalAlignment.Right;
textBlock.VerticalAlignment = VerticalAlignment.Top;
textBlock.FontSize = 12;
textBlock.Foreground = new SolidColorBrush(Colors.Black);
textBlock.TextAlignment = TextAlignment.Left;
textBlock.Background = (Brush)bc.ConvertFrom("#e0fcc4");
textBlock.FontFamily = new FontFamily("Helvetica Neue");
textBlock.FontStretch = FontStretches.UltraExpanded;
textBlock.FontStyle = FontStyles.Normal;
textBlock.Typography.NumeralStyle = FontNumeralStyle.OldStyle;
textBlock.Typography.SlashedZero = true;
sp.Children.Add(textBlock);
Responce.Children.Add(sp);
在此处输入图像描述,我的实际输出有问题
解决方案
您应该使用 aListBox
和 anObservableCollection
来代替。它更容易,默认情况下允许您滚动内容/消息。
设置ListBox.IsHitTestVisible
为False
将禁用ListBox
项目选择并删除列表外观。
主窗口.xaml.cs
public partial class MainWindow : Window
{
public static readonly DependencyProperty SmsCollectionProperty = DependencyProperty.Register(
"SmsCollection",
typeof(ObservableCollection<string>),
typeof(MainWindow),
new PropertyMetadata(default(ObservableCollection<string>)));
public ObservableCollection<string> SmsCollection
{
get => (ObservableCollection<string>) GetValue(MainWindow.SmsCollectionProperty);
set => SetValue(MainWindow.SmsCollectionProperty, value);
}
public MainWindow()
{
InitializeComponent();
this.SmsCollection = new ObservableCollection<string>();
}
private void CustomerReply(string sms)
{
// Since SmsCollection is a ObservablecCollection, add/remove/move will be reflected in the UI immediately.
this.SmsCollection.Add(sms);
}
}
主窗口.xaml
<Window>
<ListBox ItemsSource="{Binding RelativeSource={RelativeSource AncestorType=MainWindow}, Path=SmsCollection}"
IsHitTestVisible="False">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}"
Background="#e0fcc4"
FontFamily="Helvetica Neue"
...
/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Window>
推荐阅读
- c# - api作为服务运行时位图为空
- python - 在 Alembic 的 create_table 期间设置 PostgreSQL 类型
- virtual-machine - 以只读方式挂载主机文件夹?
- c# - 使用 LINQ 排除日期
- spring - 使用Kafka Streams对ReplyingKafkaTemplate进行异常管理
- git - 我的 GitLab 项目中来自 GitHub 的存储库
- python-3.x - set.pop() 真的可以删除任意值吗?
- c# - 如何调整 MSChart 滚动条
- php - 我正在尝试从 Laravel 中的选择输入中发布表单数据。(如果我使用文本框,我有什么作品)
- delphi - Delphi FMX 和 OpenStreetmap