Matt McManis Matt McManis - 3 years ago 92
C# Question

Text Erased in Duplicate Window with RichTextBox

I'm using Visual Studio 2013, C#, WPF, XAML.

This is example code to a larger project.

I have a

button
that opens a
Window
with a
RichTextBox
with the message
"Hello, World"
.

I press the
button
again, a duplicate
Window
opens but erases the text in the previous
Window
.

I think that's because both
Windows
's
RichTextBox
has the same
x:Name="rtbMessage"
.

How can I prevent text from getting erased in the previous
Window
?




Download Example:

https://www.dropbox.com/s/tq3x9fsaoclhxzm/RichTextBoxNewWindow.zip?dl=0

RichTextBox New Window




MainWidow



XAML

<Button x:Name="btnMessage"
Content="Message"
Margin="231,264,211,29"
Width="75"
Click="btnMessage_Click"/>


C#

public MessageWindow messagewindow;

// Button
// Open Message Window
//
private void btnMessage_Click(object sender, RoutedEventArgs e)
{
MainWindow mainwindow = this;

messagewindow = new MessageWindow(mainwindow);
messagewindow.Left = mainwindow.Left + 90;
messagewindow.Top = mainwindow.Top + 98;
messagewindow.Owner = Window.GetWindow(mainwindow);
messagewindow.Show();
}





MessageWindow



XAML

<RichTextBox x:Name="rtbMessage"
Margin="10,10,10,50" />


C#

public static Paragraph p = new Paragraph();

// Write Message to RichTextBox when MessageWindow Opens
//
public MessageWindow(MainWindow mainwindow)
{
InitializeComponent();

// Clear old text to prevent doubling up
rtbScript.Document = new FlowDocument(p);
rtbScript.BeginChange();
rtbScript.SelectAll();
rtbScript.Selection.Text = "";
rtbScript.EndChange();

// Write Message
rtbScript.Document = new FlowDocument(p);
rtbScript.BeginChange();
p.Inlines.Add(new Run("Hello, world."));
rtbScript.EndChange();
}

Answer Source

As we spoke in the comments.
The cause of the issue was static variable in your class definition.
Event though you had created the new object of that class the variable is shared and therefore overwritten on every call to that window messages.
As to why it is not updated in the first window I am not sure why this happens.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download