C# – WPF problems refreshing textblock bound to console.stdout


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:

StringRedir s = new StringRedir(ref ProgressTextBlock); 
this.DataContext = s; 


<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;} 
            text = text + value; 

    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"; 


Best Solution

You haven't included the code that is loading the data for the TreeView, but I'm guessing it's being done on the UI thread. If so, this will block any UI updates (including changes to the TextBlock) until it has completed.

Related Question