Search code examples
c#wpfgridchatbottextblock

want to append text-block in grid dynamically Wpf C#


i want to create Chatbot and use a Responce grid as Main chat area.whenever i used my method with different string then everytime my method override the previous textblock but i want to append my next textblock below the first one like whatsapp and any other messenger.

that is my xaml code

<Grid x:Name="Responce" HorizontalAlignment="Left" Height="315" VerticalAlignment="Top" Width="422" Margin="10,10,0,0"/>

and that one is my c# method that create textblock and add it in grid.

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);

enter image description here that i the actual output with problem


Solution

  • XAML:

    ...
    <StackPanel x:Name="RootStack">
    </StackPanel>
    ...
    

    Code behind:

    private void CustomerReply(string sms)
    {
        var textBlock = new TextBlock {Text = sms};
        //add other values here
        RootStack.Children.Add(textBlock);
    }