强制WPF控件刷新?

Coo*_*.Wu 12 wpf controls refresh

我们有两个这样的textBlock :(我们使用.NET FW 3.0)

<TextBlock Grid.Column="0" Name="tabName" Style="{StaticResource textBlockBarStyle}" HorizontalAlignment="Left">
  <TextBlock.Margin>
      <Binding Converter="{StaticResource dpiConverter}">
          <Binding.ConverterParameter>
               <Thickness Left="3" Top="6" Right="0" Bottom="0"/>
          </Binding.ConverterParameter>
      </Binding>
  </TextBlock.Margin>
</TextBlock>
Run Code Online (Sandbox Code Playgroud)

<TextBox  x:Name="txtBoxHelp" 
          IsReadOnly="True" Style="{DynamicResource txtBoxHelpStyle}" 
          IsTabStop="False" 
          Text="some text" MouseLeftButtonDown="txtBoxHelp_MouseLeftButtonDown">
     <TextBox.Margin>
        <Binding Converter="{StaticResource dpiConverter}">
            <Binding.ConverterParameter>
                 <Thickness Left="7" Top="0" Right="0" Bottom="0"/>
            </Binding.ConverterParameter>
        </Binding>
     </TextBox.Margin>
</TextBox>
Run Code Online (Sandbox Code Playgroud)

这两个textBlock在其他操作系统上运行良好,但有时会错过带有SP3的Windows XP Home版本.我们已经尝试了许多方法来刷新这些,但失败了.

我们尝试了:

  1. UpdateLayout请
  2. InvalidateVisual
  3. 将代码中的Text属性更改为绑定模式.

如何强制这些控件刷新?

小智 20

这对我们有用,无需创建新线程.它会安排在所有绑定首先更新自身时开始的操作.

           Application.Current.Dispatcher.BeginInvoke(
                DispatcherPriority.Background,
                new Action(() =>
                    {
                        // Do something here.
                    }));
Run Code Online (Sandbox Code Playgroud)


Son*_*Ali 5

在 WPF 中使控件实时更新的方法是通过 TwoWay 数据绑定。因此,请确保绑定到的所有 viewModel 属性都是依赖属性或实现 INotifyPropertyChanged (并正确处理),并且它们的 Binding.Mode = TwoWay。

查看Rudi Grobler关于 WPF 数据绑定我不知道的 10 件事

一些数据绑定文章:

  1. WPF 数据绑定 - 第 1 部分作者:Joel Ivory Johnson替代文本
  2. 一步一步迈向 WPF 数据绑定作者:Josh Smith


Coo*_*.Wu 4


Thread thread = new Thread(new ThreadStart(delegate()
                {
                    Thread.Sleep(200); // this is important ...
                    try
                    {
                        this.Dispatcher.BeginInvoke(DispatcherPriority.Send,
                            new NoArgsHandle(delegate()
                            {
                               // do something, set .Text = "some text"
                            }));
                    }
                    catch { }
                }));
                thread.Name = "thread-UpdateText";
                thread.Start();
Run Code Online (Sandbox Code Playgroud)

效果很好。