我知道这已经得到了回答,但我无法让它发挥作用。有人可以帮我解决这个问题
这是我的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>
错误讯息:
调用线程无法访问此对象,因为其他线程拥有该对象。
答案 0 :(得分: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;
}
(未经测试但你明白了)