【问题标题】:WPF RichTextBox text from bottomWPF RichTextBox 底部的文本
【发布时间】:2015-12-01 05:52:30
【问题描述】:

我正在尝试制作一个聊天窗口,例如 IRC,其中的内容从下到上显示,就像任何曾经创建的聊天窗口一样。

这是我的 xaml,没什么好看的

<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:ee="http://schemas.microsoft.com/expression/2010/effects" xmlns:ed="http://schemas.microsoft.com/expression/2010/drawing" x:Class="TestChat.Chat"
    Title="Chat" Height="700" Width="400" WindowStyle="ThreeDBorderWindow" ResizeMode="CanMinimize">

    <Grid>
        <RichTextBox x:Name="txtChat" HorizontalAlignment="Left" Height="644" Margin="0,10,0,0" VerticalAlignment="Top" Width="388" VerticalScrollBarVisibility="Auto">
            <FlowDocument />
        </RichTextBox>
    </Grid>
</Window>

我有一个后台工作人员向它添加文本

private void SendWorkerComplete(object s, ProgressChangedEventArgs args)
{
    txtChat.AppendText(args.UserState.ToString());
    txtChat.ScrollToEnd();
}

private void SendWorker_DoWork(object sender, DoWorkEventArgs e)
{
    SendWorker.ReportProgress(0, (string)e.Argument);
}

设置为底部的 VerticalContentAlignment 属性不会以这种方式呈现内容,怎么会这样呢?是否有它的属性或必须以编程方式完成?

【问题讨论】:

  • 这里有一个类似的要求。与您指定的不完全一样,但它可能对您有用:stackoverflow.com/questions/10308475/…
  • 这只会滚动到底部,但如果richtextbox为空,则无法重现此行为,我想我可以添加一堆空行并滚动到结束,然后再将输出附加到它以重现这个,但我正在寻找一种更优雅的方式来做到这一点,无论如何谢谢
  • 您能告诉我们您正在使用的 xaml 吗?
  • 当然,不过没有什么了不起的
  • 有什么理由需要 RichTextBox 吗?看我的回答。

标签: c# wpf richtextbox


【解决方案1】:

为什么要使用 RichTextBox?只需使用常规的 TextBox。

<Grid>
    <TextBox x:Name="txtChat" VerticalScrollBarVisibility="Auto" Margin="10" Text="Hello" VerticalContentAlignment="Bottom" />
</Grid>

【讨论】:

  • 它是一个聊天,所以它需要有表情,不同的字体大小,样式,颜色......你明白了
  • @FuuRe 啊!我知道了。我假设您只使用纯文本界面,因为如果我这样做,并且想要处理表情符号花哨的样式等,我绝对不会使用richtextbox。我首先构建一个包含所有相关属性(发件人、消息等)的消息类,然后构建一个自定义 xaml 控件来表示消息对象。每次消息到达时,创建一个新的消息对象并将其添加到集合中。将列表视图绑定到该集合,列表项模板是您的自定义 xaml 控件。
【解决方案2】:

您已将 margin-left 设置为 545,将富文本框移出 Window 将您的代码更改为类似这样的内容,在窗口底部显示您的控件:

<RichTextBox x:Name="txtChat" HorizontalAlignment="Stretch" Height="42" VerticalAlignment="Bottom" Width="auto" VerticalScrollBarVisibility="Auto" Background="Yellow">
        <FlowDocument />
</RichTextBox>

【讨论】:

    猜你喜欢
    • 2011-09-05
    • 1970-01-01
    • 1970-01-01
    • 2014-11-02
    • 2015-11-12
    • 1970-01-01
    • 1970-01-01
    • 2014-12-23
    • 2011-07-27
    相关资源
    最近更新 更多