wpf 强制 TextBox 刷新
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18446785/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
force TextBox to refresh
提问by user1151923
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
我有一个绑定到字符串属性的普通 wpf TextBox 控件。我需要在绑定或更新 .Text 属性后立即更新显示的文本。我试过了
((TextBox)sender).GetBindingExpression(TextBox.TextProperty).UpdateSource();
((TextBox)sender).GetBindingExpression(TextBox.TextProperty).UpdateTarget();
in the TextChanged event handler.
在 TextChanged 事件处理程序中。
I've tried UpdateSourceTrigger=Expliciton the binding. I've tried
我试过UpdateSourceTrigger=Explicit绑定。我试过了
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:
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" />
回答by denis morozov
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.
如果您的方法做了大量工作,则它可能会保持 UI 线程 () 的执行顺序)。无论您在该方法中做什么 - 在后台线程中进行。
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.
只要确保在该方法中您触摸任何 UI 元素,您在 UI 线程上进行操作,否则您将崩溃。另一种让 UI 线程知道的可能更好的方法是 RaisePropertyChanged 您希望绑定知道,而不是直接操作 UI 元素。
回答by recurzive
You need to use TwoWay binding instead of changing the TextBox's value expicitly and you need to implement the INotifyPropertyChangedon the binded data's class.
您需要使用 TwoWay 绑定而不是显式更改 TextBox 的值,并且您需要在绑定数据的类上实现INotifyPropertyChanged。
回答by Croko
Try the following code sequence, it worked for me-
尝试以下代码序列,它对我有用-
Textblock1.Text = "ABC";
System.Windows.Forms.Application.DoEvents();
MainWindow.InvalidateVisual();
System.Threading.Thread.Sleep(40);

