我的MainUI中有一个列表框。我通过以下代码添加项目:
for (int i = 0; i < 50; i++) {
ListBoxItem sub1 = new ListBoxItem();
if (i % 2 == 0) {
sub1.Foreground = Brushes.Red;
} else {
sub1.Foreground = Brushes.Green;
}
sub1.Content = i;
this.listStatus.Items.Add(sub1);
}
之后,我想将这些值保存为红色和绿色的文件。 我尝试将它们写入.doc文件购买我只能通过以下代码获得黑色字符:
int lisboxcounter = 0;
FileStream fs = new FileStream(@"D:\Test.doc", FileMode.OpenOrCreate);
StreamWriter s = new StreamWriter(fs);
while (this.listStatus.Items.Count > lisboxcounter) {
s.WriteLine(this.listStatus.Items[lisboxcounter].ToString());
lisboxcounter++;
}
s.Close();
fs.Close();
和值System.Windows.Controls.ListBoxItem:
0。
我怎样才能写出价值; 0,1,2,3 ...... 红色和绿色?
非常感谢。
答案 0 :(得分:1)
最好的办法是写入RichTextBox,然后将内容保存到RTF文件中。
<StackPanel Orientation="Horizontal"
Grid.Row="0">
<Button Width="80"
Content="Load"
Name="_loadButton"
Click="_loadButton_Click" />
<Button Width="80"
Content="Save"
Name="_saveButton"
Click="_saveButton_Click" />
</StackPanel>
<RichTextBox Grid.Row="1" Name="_rtfBox" VerticalScrollBarVisibility="Auto" />
</Grid>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
using System.Diagnostics;
namespace SaveAsRtf
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void _loadButton_Click(object sender, RoutedEventArgs e)
{
var newDoc = new FlowDocument();
for (int i = 0; i < 50; i++)
{
Paragraph newPara = new Paragraph();
if (i % 2 == 0)
{
newPara.Foreground = Brushes.Red;
}
else
{
newPara.Foreground = Brushes.Green;
}
newPara.Inlines.Add(new Run(i.ToString()));
newDoc.Blocks.Add(newPara);
}
_rtfBox.Document = newDoc;
}
private void _saveButton_Click(object sender, RoutedEventArgs e)
{
string temp = System.IO.Path.GetTempFileName() + ".rtf";
using (FileStream fs = File.Create(temp))
{
TextRange text = new TextRange(_rtfBox.Document.ContentStart, _rtfBox.Document.ContentEnd);
text.Save(fs, DataFormats.Rtf);
}
Process.Start(temp);
}
}
}