首页 > 解决方案 > 想要在网格中动态追加文本块 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);

在此处输入图像描述,我的实际输出有问题

标签: c#wpfgridchatbottextblock

解决方案


您应该使用 aListBox和 anObservableCollection来代替。它更容易,默认情况下允许您滚动内容/消息。
设置ListBox.IsHitTestVisibleFalse将禁用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>

推荐阅读