C# 在另一个线程中使用XAML中定义的控件

C# 在另一个线程中使用XAML中定义的控件,c#,wpf,xaml,C#,Wpf,Xaml,我正在玩找到的库,它有助于在多个线程上呈现UI。这个示例运行良好,并且做了它应该做的事情,但是我想稍微修改一下 在示例中,将在单独线程上呈现的可视元素在代码隐藏中定义/创建。以下是一些示例代码: XAML: 因此OnLoaded创建并设置VisualWrapper的子属性。我想做的是允许用户在XAML中定义要直接分配给Child的控件,例如: <local:VisualWrapper Grid.Column="0" Width="200" Height="100" x:Name="Pla

我正在玩找到的库,它有助于在多个线程上呈现UI。这个示例运行良好,并且做了它应该做的事情,但是我想稍微修改一下

在示例中,将在单独线程上呈现的可视元素在代码隐藏中定义/创建。以下是一些示例代码:

XAML:



因此OnLoaded创建并设置VisualWrapper的子属性。我想做的是允许用户在XAML中定义要直接分配给Child的控件,例如:

<local:VisualWrapper Grid.Column="0" Width="200" Height="100" x:Name="Player1"/>               
  <local:VisualWrapper.ChildSource>
    <Button>TEST</Button>
  </local:VisualWrapper.ChildSource>
</View:VisualWrapper>
我得到一个错误:“调用线程无法访问这个对象,因为它是另一个线程拥有的。”。我无法让它工作,我想知道这是否可能



我尝试在getter中使用Dispatcher:

public FrameworkElement ChildSource
{
    get { return (FrameworkElement)Dispatcher.Invoke((Delegate)GetValue(ChildSourceProperty)); }
    set { this.SetValue(ChildSourceProperty, value); }
}
但那没用。我的感觉是需要一些Disaptcher.Invoke,但我不确定在哪里

我想做的事能完成吗?

不行

WPF创建具有线程关联性的对象,这些对象只能从创建它们的线程中使用。这意味着,如果要在线程之间拆分UI,则必须在将要使用它的线程上创建每个控件

<local:VisualWrapper Grid.Column="0" Width="200" Height="100" x:Name="Player1"/>               
  <local:VisualWrapper.ChildSource>
    <Button>TEST</Button>
  </local:VisualWrapper.ChildSource>
</View:VisualWrapper>
public FrameworkElement ChildSource
{
    get { return (FrameworkElement)this.GetValue(ChildSourceProperty); }
    set { this.SetValue(ChildSourceProperty, value); }
}
public FrameworkElement ChildSource
{
    get { return (FrameworkElement)Dispatcher.Invoke((Delegate)GetValue(ChildSourceProperty)); }
    set { this.SetValue(ChildSourceProperty, value); }
}