[英]Access RichTextBox from another class
我是新手,正在嘗試在 c# 中做一些事情,但我不知道如何解決這個問題。
我的 MainWindow.xaml.cs 我有一個名為 RTB 的 RichTextBox,我想將其保存到文本文件中。
我創建了新文件 Saving.cs,我會在其中寫入保存所需的所有內容。 這是我的代碼。
保存.cs
public string VarName = "";
public void Save()
{
MainWindow main = new MainWindow();
TextRange range = new TextRange(main.RTB.Document.ContentStart, main.RTB.Document.ContentEnd);
FileStream stream = new FileStream(VarName, FileMode.Create);
range.Save(stream, DataFormats.Text);
stream.Close();
}
MainWindow.xaml.cs
private void Button_Save(object sender, RoutedEventArgs e)
{
saveDoc.VarName = SaveName.Text + ".txt";
saveDoc.Save();
}
一切正常,只是保存的文檔中沒有任何內容。 我的問題是我真的不知道如何從不同的文件訪問 RTB。 當我將此代碼放入 MainWindow.xaml.cs 時它起作用,但當它在不同的文件(如 Saving.cs)中時不起作用。
我也不知道在我的 Saving.cs“MainWindow main = new MainWindow();”中是否可以或者如何解決這個問題。
感謝您的幫助好心的陌生人。
我希望這些代碼片段可以幫助解決您的問題
主窗口.xaml.cs:
private void Button_Click(object sender, RoutedEventArgs e)
{
// Note: Please dont forget about OOP,
// dont use 'public' mode on class fields (VarName)
SaveDoc.MyProperty = SaveName.Text + ".txt";
TextRange range = new TextRange(RTB.Document.ContentStart,RTB.Document.ContentEnd);
//You can pass this 'range' field as a parameter to Class 'SaveDoc'
SaveDoc.Save(range);
}
保存.cs:
class SaveDoc
{
private static string VarName;
//Use Properties to access fields from another classes
public static string MyProperty
{
get { return VarName; }
set { VarName = value; }
}
// Here you can pass the 'range' field from MainWindow as a parameter
public static void Save(TextRange range)
{
FileStream stream = new FileStream(VarName, FileMode.Create);
range.Save(stream, DataFormats.Text);
stream.Close();
}
}
你也可以這樣做:
主窗口.xaml.cs:
private void Button_Click(object sender, RoutedEventArgs e)
{
// Note: Please dont forget about OOP,
// dont use 'public' mode on class fields (VarName)
SaveDoc.MyProperty = SaveName.Text + ".txt";
string range = new TextRange(RTB.Document.ContentStart,RTB.Document.ContentEnd).Text;
//You can pass this 'range' field as parameter to Class 'SaveDoc'
SaveDoc.Save(range);
}
保存.cs:
class SaveDoc
{
private static string VarName;
//Use Properties to access fields from another classes
public static string MyProperty
{
get { return VarName; }
set { VarName = value; }
}
// Here you can pass the 'range' field from MainWindow as a parameter
public static void Save(string range)
{
// Standart algorithm to write something in file:
FileStream stream = new FileStream(VarName, FileMode.Create);
//convert string to bytes
byte[] buf = Encoding.Default.GetBytes(range);
// writing an array of bytes to a file
stream.Write(buf, 0, buf.Length);
stream.Close();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.