【发布时间】:2018-05-10 04:44:20
【问题描述】:
所以我目前正在尝试将消息从进程打印到富文本框,除了我希望它以红色文本显示错误消息和以绿色显示正常消息之外,一切都很好。
由于某种原因,它都是绿色的,我认为这是因为我正在绑定前景而不是附加到 RTB,但我不确定。
如何正确地将错误消息变为红色而正常消息变为绿色。
MainWindow.cs
public partial class MainWindow : Window
{
static Server server = new Server();
private readonly Thread ConsoleThread = new Thread(() => { server.Start("Start.bat"); });
public MainWindow()
{
InitializeComponent();
DataContext = server;
}
private void ButtonStart(object sender, RoutedEventArgs e)
{
ConsoleThread.Start();
}
private void tbConsole_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
=> tbConsole.ScrollToEnd();
}
服务器.cs
class Server : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private Process pServer = new Process();
private Brush color;
public Brush MessageColor
{
get { return color; }
set
{
color = value;
OnPropertyChanged("MessageColor");
}
}
private string outStream;
public string OutputStream
{
get { return outStream; }
set
{
if (!string.IsNullOrEmpty(value))
{
outStream += value + Environment.NewLine;
OnPropertyChanged("OutputStream");
}
}
}
public void Start(string Path)
{
pServer.StartInfo.FileName = Path;
pServer.StartInfo.UseShellExecute = false;
pServer.StartInfo.RedirectStandardOutput = true;
pServer.StartInfo.RedirectStandardError = true;
pServer.OutputDataReceived += OKDataReceived;
pServer.ErrorDataReceived += ErrorDataReceived;
pServer.Start();
pServer.BeginOutputReadLine();
pServer.BeginErrorReadLine();
}
private void OKDataReceived(object sender, DataReceivedEventArgs e)
{
MessageColor = Brushes.Green;
OutputStream = e.Data;
}
private void ErrorDataReceived(object sender, DataReceivedEventArgs e)
{
MessageColor = Brushes.Red;
OutputStream = e.Data;
}
public void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handle = PropertyChanged;
if (handle != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
XAML
<Grid>
<Button Click="ButtonStart" Content="Start" Margin="325,63,353,319"/>
<xctk:RichTextBox FontSize="5" Name="tbConsole" Margin="143,149,164,81" BorderBrush="Gray" Padding="10" ScrollViewer.VerticalScrollBarVisibility="Auto" Text="{Binding Path=OutputStream, Mode=TwoWay}" Foreground="{Binding Path=MessageColor}" />
</Grid>
【问题讨论】:
标签: c# .net xaml mvvm data-binding