这是工作代码(但在 UI 线程上):
<ContentControl
Width="{Binding Path=ActualWidth, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListView}}}"
Focusable="True"
HorizontalAlignment="Right"
Content="{Binding Work}" >
</ContentControl>
这是我尝试编写的代码,但它不起作用:(代码隐藏)
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
并将其放置在 Grid 中,Grid 位于具有多个 ContentControls
的 listview
内。)如图所示解决方案正在崩溃,因为另一个线程拥有 MainGrid
。
有人对此有好主意吗? (希望在另一个线程上执行此操作,因为 ContentControl
很重,创建布局需要 3 秒。这是一个根据参数创建自身的通用 View 。)
编辑:
主要问题是在创建这些 View 期间,我的整个应用程序挂起。这是非常不受欢迎的。我的目标是将此工作负载转移到另一个(或多个)其他线程。
最佳答案
您可以使用 IsAsync
属性强制在不同的线程上执行绑定(bind)。
Content="{Binding Work, IsAsync=True}"
这将在新线程上执行与 Work
的绑定(bind),完成后将填充内容。您无需为代码隐藏的内容操心。
您可以在操作中找到一个很好的教程 here .
关于c# - 在另一个线程 wpf 上创建 UI 重元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30709011/