在另一个线程wpf上创建UI heavy元素

本文关键字:UI heavy 元素 创建 另一个 线程 wpf | 更新日期: 2023-09-27 17:54:36

这是工作代码(但在UI线程上):

<ContentControl 
                Width="{Binding Path=ActualWidth, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListView}}}" 
                Focusable="True"  
                HorizontalAlignment="Right" 
                Content="{Binding Work}" >
            </ContentControl>

这是我想做的代码,但它不起作用:(codebehind)

            InitializeComponent();
            var thread = new Thread(
                () =>
                {
                    var a = new ContentControl { Focusable = true, HorizontalAlignment = HorizontalAlignment.Right };
                    var binding = new Binding { Path = new PropertyPath("Work"), };
                    a.SetBinding(ContentProperty, binding);
                    MainGrid.Dispatcher.Invoke(new Action(() => { MainGrid.Children.Add(a); }));
                }) { IsBackground = true };
            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();

我的目标是创建一个ConentControl并将其放置在网格中,这是在具有多个ContentControlslistview内部。)所示的解决方案正在崩溃,因为不同的线程拥有MainGrid。有人有什么好主意吗?(我喜欢在另一个线程上这样做,因为ContentControl很重,像3秒创建布局。它是一个通用视图,根据参数创建自己)

编辑:

主要问题是,在创建这些视图期间,我的整个应用程序挂起了。这是非常不需要的。我的目标是将此工作负载转移到另一个(或多个)其他线程。

在另一个线程wpf上创建UI heavy元素

您可以使用IsAsync属性强制在不同的线程上执行绑定。

Content="{Binding Work, IsAsync=True}"

这将在一个新线程上执行到Work的绑定,并在完成后填充内容。你不需要为你的代码隐藏的东西而烦恼。

你可以在这里找到一个很好的教程。