Reputation: 1872
I have a normal wpf TextBox control bound to a string property. I need the displayed text to be updated immediately after the binding or the .Text property is updated. I have tried
((TextBox)sender).GetBindingExpression(TextBox.TextProperty).UpdateSource();
((TextBox)sender).GetBindingExpression(TextBox.TextProperty).UpdateTarget();
in the TextChanged event handler.
I've tried UpdateSourceTrigger=Explicit
on the binding. I've tried
Application.Current.Dispatcher.BeginInvoke(
DispatcherPriority.Input,
new Action(() =>
{
statusTextBox.Text = "newValue";
}));
and many different combinations of these. But the text displayed changes only once the method I update the textbox from exits.
XAML:
<TextBox x:Name="txBox" Height="150" Margin="0,0,0,0" VerticalAlignment="Top" TextWrapping="Wrap" VerticalScrollBarVisibility="Auto" AcceptsReturn="True" VerticalContentAlignment="Top" Text="{Binding TextProperty}"Width="200" />
Upvotes: 5
Views: 25128
Reputation: 97
Try the following code sequence, it worked for me-
Textblock1.Text = "ABC";
System.Windows.Forms.Application.DoEvents();
MainWindow.InvalidateVisual();
System.Threading.Thread.Sleep(40);
Upvotes: -1
Reputation: 9
You need to use TwoWay binding instead of changing the TextBox's value expicitly and you need to implement the INotifyPropertyChanged on the binded data's class.
Upvotes: 0
Reputation: 6316
your method if it's doing alot of work is probably holding the UI thread () the order of execution). Whatever you are doing in that method - do it in the background thread.
private void SomeMethod()
{
Task.Factory.StartNew(() =>
{
/// do all your logic here
//Update Text on the UI thread
Application.Current.Dispatcher.BeginInvoke( DispatcherPriority.Input,
new Action(() => { statusTextBox.Text = "newValue";}));
//continue with the rest of the logic that take a long time
});
Just make sure that if in that method you are touching any UI elements, you do it on the UI thread, otherwise you will get a crash. Another, possibly better way to let UI thread know is to RaisePropertyChanged that you want the binding to know about, instead of directly manipulating the UI element.
Upvotes: 6