强制刷新文本框

use*_*923 4 c# wpf textbox

我有一个绑定到字符串属性的普通wpf TextBox控件。我需要在绑定或.Text属性更新后立即更新显示的文本。我试过了

((TextBox)sender).GetBindingExpression(TextBox.TextProperty).UpdateSource();
((TextBox)sender).GetBindingExpression(TextBox.TextProperty).UpdateTarget();
Run Code Online (Sandbox Code Playgroud)

在TextChanged事件处理程序中。

我已经尝试UpdateSourceTrigger=Explicit过绑定。我试过了

Application.Current.Dispatcher.BeginInvoke(
    DispatcherPriority.Input,
     new Action(() =>
     {
         statusTextBox.Text = "newValue";
     }));
Run Code Online (Sandbox Code Playgroud)

以及这些的许多不同组合。但是,仅当我从出口更新文本框的方法后,显示的文本才会更改。

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" />
Run Code Online (Sandbox Code Playgroud)

den*_*zov 5

您的方法(如果正在执行大量工作)可能会使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
                    });
Run Code Online (Sandbox Code Playgroud)

只要确保如果您使用该方法触摸了任何UI元素,就可以在UI线程上进行操作,否则会崩溃。让UI线程知道的另一种可能更好的方法是,使绑定知道有关的RaisePropertyChanged,而不是直接操作UI元素。