在文本框中动态显示文件内容[WPF]

Dynamicly showing file contents in textbox [WPF]

我正在构建一个 WPF 应用程序,其中有一个文本框,但问题是此文本框需要将文件的内容作为文本获取,只有 txt 文件也在不断写入。

我做了一个 class 来处理这个问题:

public class ChatHandler
{
    public FileStream stream;
    StreamWriter writer;
    StreamReader reader;

    public ChatHandler()
    {
        stream = new FileStream(@"chat/" + DateTime.Today.ToString("d") + ".txt", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
        writer = new StreamWriter(stream);
        reader = new StreamReader(stream);
    }

    public void Write(string line)
    {
        writer.WriteLineAsync(line);
        writer.Flush();
    }

    public string Read()
    {
        string tmp = "";
        string line;
        while((line = reader.ReadLine()) != null){
            tmp += line + '\n';
        }
        return tmp;
    }
}

我有一个带有文本框的用户控件:

public partial class ChatScreen : UserControl
{
    MainWindow parent;
    ChatHandler chatHandler;
    BackgroundWorker worker;
    public ChatScreen()
    {
        InitializeComponent();
        chatHandler = new ChatHandler();

        worker = new BackgroundWorker();
        worker.WorkerSupportsCancellation = true;
        worker.DoWork += new DoWorkEventHandler(run);
    }

    private void load()
    {

    }

    private void write(string text)
    {
        if (chat.Text != text && text != "")
        {
            chat.Text = text;
        }
    }

    private void run(object sender, DoWorkEventArgs e)
    {
        BackgroundWorker bg = sender as BackgroundWorker;
        while (!bg.CancellationPending)
        {
            chat.Dispatcher.BeginInvoke((Action)(()=>{
                write(parent.Handler.Read());                    
            }));
            Thread.Sleep(100);
        }
    }

    private void chat_Loaded(object sender, RoutedEventArgs e)
    {
        parent = (MainWindow)Window.GetWindow(this);
        if (!worker.CancellationPending)
        {
            worker.RunWorkerAsync();
        }

    }

    private void chat_Unloaded(object sender, RoutedEventArgs e)
    {
        worker.CancelAsync();
    }
}

但现在出现了问题:文本从未更改过,设置一次后就再也没有更改过:(尽管在文本文件中添加了行。

xaml 文件的内容是:

<UserControl x:Class="tantiBotv2.ChatScreen"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         mc:Ignorable="d" 
         d:DesignHeight="381" d:DesignWidth="641" Loaded="chat_Loaded" Unloaded="chat_Unloaded">
    <Grid Style="{StaticResource ContentRoot}">
        <ScrollViewer HorizontalScrollBarVisibility="Disabled" VerticalScrollBarVisibility="Visible">
            <TextBox IsReadOnly="true" Margin="0,0,0,0" TextWrapping="Wrap" Name="chat" IsReadOnlyCaretVisible="false"/>
        </ScrollViewer>
    </Grid>
</UserControl>

谁能帮我解决这个问题?

我无法重现您的确切问题,我遇到的问题是文本文件中只出现了新文本。这是因为 StreamReader 是一个成员变量,而且它是一个只转发 reader。您可以通过以下方式解决此问题:

public string Read()
{
    using (var stream = new FileStream(@"chat.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
    {
        using (var reader = new StreamReader(stream))
        {
            string tmp = "";
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                tmp += line + '\n';
            }
            return tmp;
        }
    }
}

编辑:问题得到进一步澄清后:

XAML:

<Grid>

    <Grid.ColumnDefinitions>
        <ColumnDefinition></ColumnDefinition>
        <ColumnDefinition></ColumnDefinition>
    </Grid.ColumnDefinitions>

    <Grid.RowDefinitions>
        <RowDefinition Height="*"></RowDefinition>
    </Grid.RowDefinitions>

    <DockPanel Grid.Column="0" LastChildFill="True">
        <Label DockPanel.Dock="Top">IRC channel simulator</Label>
        <Button DockPanel.Dock="Top" Click="Button_Click">Send Chat</Button>
        <ScrollViewer HorizontalScrollBarVisibility="Disabled" VerticalScrollBarVisibility="Visible">
            <TextBox Background="AliceBlue" AcceptsReturn="True" Margin="0,0,0,0" TextWrapping="Wrap" Name="chatWriter" IsReadOnlyCaretVisible="false" />
        </ScrollViewer>
    </DockPanel>

    <ScrollViewer Grid.Column="1" HorizontalScrollBarVisibility="Disabled" VerticalScrollBarVisibility="Visible">
        <TextBox IsReadOnly="true" Margin="0,0,0,0" TextWrapping="Wrap" Name="chat" IsReadOnlyCaretVisible="false"/>
    </ScrollViewer>
</Grid>

代码隐藏 Xaml:

public partial class MainWindow : Window
{
    ChatHandler chatHandler;
    BackgroundWorker worker;

    public MainWindow()
    {
        InitializeComponent();

        chatHandler = new ChatHandler();

        worker = new BackgroundWorker();
        worker.WorkerSupportsCancellation = true;
        worker.DoWork += new DoWorkEventHandler(run);
    }

    private void write(string text)
    {
        if (chat.Text != text && text != "")
        {
            chat.Text = text;
        }
    }

    private void run(object sender, DoWorkEventArgs e)
    {
        BackgroundWorker bg = sender as BackgroundWorker;
        while (!bg.CancellationPending)
        {
            chat.Dispatcher.BeginInvoke((Action)(() => {
                write(chatHandler.Read());
            }));
            Thread.Sleep(100);
        }
    }

    private void chat_Loaded(object sender, RoutedEventArgs e)
    {
        if (!worker.CancellationPending)
        {
            worker.RunWorkerAsync();
        }
    }

    private void chat_Unloaded(object sender, RoutedEventArgs e)
    {
        worker.CancelAsync();
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        chatHandler.Write(chatWriter.Text);
    }
}

ChatHandler.cs

public class ChatHandler
{
    public FileStream stream;
    //StreamWriter writer;
    //StreamReader reader;

    public ChatHandler()
    {
        stream = new FileStream(@"chat.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
        //writer = new StreamWriter(stream);
        //reader = new StreamReader(stream);
    }

    public void Write(string line)
    {
        using (var fileStream = new FileStream(@"chat.txt", FileMode.Append, FileAccess.Write, FileShare.ReadWrite))
        {
            using (var writer = new StreamWriter(fileStream))
            {
                writer.WriteLineAsync(line);
                writer.Flush();
            }
        }
    }

    public string Read()
    {
        using (var fileStream = new FileStream(@"chat/" + DateTime.Today.ToString("d") + ".txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
        {
            using (var reader = new StreamReader(fileStream))
            {
                string tmp = "";
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    tmp += line + '\n';
                }
                return tmp;
            }
        }
    }
}