【问题标题】:cannot update wpf control from non UI thread无法从非 UI 线程更新 wpf 控件
【发布时间】:2015-09-26 21:12:26
【问题描述】:

我知道这已得到解答,但我无法让它工作。有人能帮我解决这个问题吗

这是我的 xaml 类:

namespace Windamow
{
/// <summary>
/// Interaction logic for DynamoWindow.xaml
/// </summary>
public partial class DynamoWindow : Window
{
    public DynamoWindow()
    {
        InitializeComponent();
    }
    public void setBrowserURL(string URL)
    {
        browser.Source = new Uri(URL);
    }
    public void setBrowserFromString(string HTMLString)
    {
        browser.NavigateToString(HTMLString);
    }
}
}

然后我尝试更新显示如下的 html 字符串:

namespace Windamow
{
public class Windamow
{

    private DynamoWindow window;

    internal void ThreadProc()
    {
        window = new DynamoWindow();

        window.ShowDialog();
    }

    internal Windamow()
    {
        Thread t = new Thread(ThreadProc);
        t.SetApartmentState(ApartmentState.STA);
        t.Start();
    }

    public static DynamoWindow MakeWindow(bool launch, string html)
    {
        if (launch)
        {
            Windamow mow = new Windamow();

            var action = new Action(() => mow.window.setBrowserFromString(html));
            Application.Current.Dispatcher.BeginInvoke(
            DispatcherPriority.Input,
            action);

            return mow.window;
        }
        else
        {
            return null;
        }
    }
}
}

xaml:

<Window x:Class="Windamow.DynamoWindow"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         mc:Ignorable="d" 
         d:DesignHeight="300" d:DesignWidth="300">
<Grid>
    <WebBrowser x:Name="browser" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"/>
</Grid>

错误信息:

调用线程无法访问此对象,因为其他线程拥有它。

【问题讨论】:

  • 关联的 xaml 在哪里?
  • @isi 更新了问题。我的坏

标签: c# wpf multithreading data-binding


【解决方案1】:

问题就在这里:

var action = new Action(() => mow.window.setBrowserFromString(html));

此代码将尝试从 主 UI 线程 访问 window 对象,而它是在另一个线程上创建并关联到另一个线程,即您自己创建的 t

根据您的用例,您可以简单地尝试以下操作:

public DynamoWindow(string html)
{
    InitializeComponent();

    setBrowserFromString(html);
}
...
if (launch)
{
    Windamow mow = new Windamow(html);

    return mow.window;
}

(未测试,但你明白了)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-10
    • 1970-01-01
    • 2010-12-11
    • 2014-08-24
    • 1970-01-01
    相关资源
    最近更新 更多