如何从Dispatcher线程访问单独的线程生成的WPF UI元素



我需要使用诸如FixedDocument、FlowDocument、PageContent、BlockUIContainer等wpf UI元素生成打印预览(长预览)。为了保持UI的响应性,我在一个单独的Thread类线程上完成了这一部分(BackgroundWorker不起作用,因为我需要一个STA线程)。到目前为止一切都还可以
但在显示打印预览后,我现在需要打印,在生成的预览上单击"打印"图标会引发臭名昭著的"调用线程无法访问此对象,因为其他线程拥有它。"异常。那么,有什么办法吗?

编辑(代码):

Dispatcher.CurrentDispatcher.Invoke(new Action(() =>  
    {  
        Thread thread = new Thread(() =>  
            {  
                FixedDocument document = renderFlowDocumentTemplate(report);  
                PrintPreview preview = new PrintPreview();  
                preview.WindowState = WindowState.Normal;  
                preview.documentViewer.Document = document;  
                preview.ShowDialog();  
            });  
        thread.SetApartmentState(ApartmentState.STA);  
        thread.Start();  
    }));`

在这里,RenderFlowDocumentTemplate()生成打印预览(包含UI元素),并用Report数据填充它们。PrintPreview是一个自定义窗口,它包含一个DocumentViewer元素,该元素实际上保存并显示预览,并包含"打印"图标,单击该图标后,我会得到PrintDialog窗口。

编辑(XAML):

<cw:CustomWindow x:Class="MyApp.Reports.PrintPreview"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:cw="clr-namespace:MyApp.UI.CustomWindows;assembly=MyApp.UI.CustomWindows">    
    <DocumentViewer Margin="0,30,0,0" Name="documentViewer"></DocumentViewer>
</cw:CustomWindow>`

最简单的方法是.

Action a = () =>
{
    //Code from another thread.
};
Dispatcher.BeginInvoke(a);

我不久前就联系上了这个问题,我认为问题是打印预览对话框需要在主线程上。

发现另一个人也有同样的问题——在不同的UI线程中打印DocumentViewer的内容。只是走了同样的路。这里的代码是一个真正的救世主
现在我不想从Dispatcher线程访问辅助线程生成的UI元素,而是在辅助线程上执行打印过程的其余部分。没有UI元素的跨线程"VerifyAccess",而且工作顺利。:)

还有另一个"窍门"。。。

我经常遇到同样的问题。例如,我尝试将FrameworkElement绑定到ContentPresenter。我的解决方案是,我使用ItemsControl代替ContentPresenter,并将我的单个FrameworkElement绑定到只有一个项的ObservableCollection<FrameworkElement>上。之后,没有问题

我写了这个简单的片段,我没有任何经验,但我对它进行了一些测试,它似乎运行得很好。

/// <summary>
/// Creates UI element on a seperate thread and transfers it to
/// main UI thread. 
/// 
/// Usage; if you have complex UI operation that takes a lot of time, such as XPS object creation.
/// </summary>
/// <param name="constructObject">Function that creates the necessary UIElement - will be executed on new thread</param>
/// <param name="constructionCompleted">Callback to the function that receives the constructed object.</param>
public void CreateElementOnSeperateThread(Func<UIElement> constructObject, Action<UIElement> constructionCompleted)
{
    VerifyAccess();
    // save dispatchers for future usage.
    // we create new element on a seperate STA thread
    // and then basically swap UIELEMENT's Dispatcher.
    Dispatcher threadDispatcher = null;
    var currentDispatcher = Dispatcher.CurrentDispatcher;
    var ev = new AutoResetEvent(false);
    var thread = new Thread(() =>
        {
            threadDispatcher = Dispatcher.CurrentDispatcher;
            ev.Set();
            Dispatcher.Run();
        });
    thread.SetApartmentState(ApartmentState.STA);
    thread.IsBackground = true;
    thread.Start();
    ev.WaitOne();
    threadDispatcher.BeginInvoke(new Action(() =>
        {
            var constructedObject = constructObject();
            currentDispatcher.BeginInvoke(new Action(() =>
                {
                    var fieldinfo = typeof (DispatcherObject).GetField("_dispatcher",
                                                                       BindingFlags.NonPublic |
                                                                       BindingFlags.Instance);
                    if (fieldinfo != null)
                        fieldinfo.SetValue(constructedObject, currentDispatcher);
                    constructionCompleted(constructedObject);
                    threadDispatcher.BeginInvokeShutdown(DispatcherPriority.Normal);
                }), DispatcherPriority.Normal);
        }), DispatcherPriority.Normal);
}

这里是用法:

 CreateElementOnSeperateThread(() =>
        {
            // running on new temp dispatcher.
            var loadsOfItems = new List<int>();
            for(var i = 0; i < 100000; i++)
                loadsOfItems.Add(i+12);

            var dataGrid = new DataGrid {ItemsSource = loadsOfItems, Width = 500, Height = 500};
            dataGrid.Measure(new Size(500, 500));
            dataGrid.Arrange(new Rect(0, 0, 500, 500));
            return dataGrid;
        }, result => SampleGrid.Children.Add(result));

在这种情况下使用dispatcher类。Dispatcher类具有invoke和beginInvoke方法。其允许使用调度进程将请求发送到当前线程。您需要做的是使用代理创建如下调用

  App.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() =>
{
//you code goes here.
 }));

begin调用异步处理您的调用。

最新更新