I am building a small wpf app in C#. When a button gets clicked a third party dll function constructs a tree like object. This object is bound to a treeview. This works fine but takes a bit of time to load. As the dll function constructs the object it prints progress info to the console. I want to redirect this into a TextBlock so that the user gets to see the progress messages.
My window ctor looks like this:
InitializeComponent(); StringRedir s = new StringRedir(ref ProgressTextBlock); Console.SetOut(s); Console.SetError(s); this.DataContext = s;
xaml:
<
TextBlock Text="{Binding Path=Text}" Width="244" x:Name="ProgressTextBlock" TextWrapping="Wrap" /><
TreeView >...<
/TreeView>
The StringRedir class is shown below. The problem is the TextBlock for some reason does not get updated with the messages until the TreeView gets loaded. Stepping through I see the Text property being updated but the TextBlock is not getting refreshed. I added a MessageBox.Show () at the point where Text gets updated and this seems to cause the window to refresh each time and I am able to see each message. So I guess I need some way to explicitly refresh the screen...but this doesnt make sense I thought the databinding would cause a visual refresh when the property changed. What am I missing here? How do I get it to refresh? Any advice is appreciated!
public class StringRedir : StringWriter , INotifyPropertyChanged
{
private string text;
private TextBlock local;
public string Text {
get{ return text;}
set{
text = text + value;
OnPropertyChanged("Text");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
public StringRedir(ref TextBlock t)
{
local = t;
Text = "";
}
public override void WriteLine(string x)
{
Text = x +"\n";
//MessageBox.Show("hello");
}
}