WPF多线程:Dispatcher异常

时间:2014-10-01 16:05:08

标签: dispatcher

我是WPF的新手,我注意到你无法直接从另一个线程访问WPF控件。相反,您必须使用Dispatcher。我已经阅读了stackoverflow中的一些文章和问题,但仍然不知道为什么下一个代码不起作用。

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        System.Threading.Thread thread = new System.Threading.Thread(
        new System.Threading.ThreadStart(
          delegate()
          {
              TransformGroup transform = new TransformGroup();

              RotateTransform rot = new RotateTransform(45);
              TranslateTransform trans = new TranslateTransform(500, 500);


              transform.Children.Add(rot);
              transform.Children.Add(trans);

              bOne.Dispatcher.Invoke(
                        System.Windows.Threading.DispatcherPriority.Normal,
                        new Action(
                          delegate()
                          {
                              bOne.RenderTransform = transform;
                          }
                      ));
                  }
              ));


        thread.Start();
    }
}

其中xaml是:

<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:Custom="http://schemas.microsoft.com/surface/2008" x:Class="Prueba.MainWindow"
    Title="MainWindow" Height="350" Width="525">
<Grid>

    <Custom:SurfaceButton Name="bOne" Content="SurfaceButton" HorizontalAlignment="Left" Margin="0,0,0,0" VerticalAlignment="Top"/>
</Grid>
</Window>

尝试修改bOne.RenderTransform时仍然抛出异常。

1 个答案:

答案 0 :(得分:0)

发现问题,我在这里发布了正确的版本。

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        System.Threading.Thread thread = new System.Threading.Thread(
        new System.Threading.ThreadStart(
          delegate()
          {


              bOne.Dispatcher.Invoke(
                        System.Windows.Threading.DispatcherPriority.Normal,
                        new Action(
                          delegate()
                          {
                              TransformGroup transform = new TransformGroup();

                              RotateTransform rot = new RotateTransform(45);
                              TranslateTransform trans = new TranslateTransform(100, 100);


                              transform.Children.Add(rot);
                              transform.Children.Add(trans);

                              bOne.RenderTransform = transform;
                          }
                      ));
                  }
              ));


        thread.Start();
    }
}

我没有意识到转换必须在调用中。