I'd like to receive callbacks开发者_运维技巧 from Javascript code to my Silverlight host without using ScriptableAttribute. I've seen it done before, but I couldn't work out how they did it. Has anyone got any ideas? Thanks
Simple enough use:-
HtmlPage.Window.Invoke("someJavascriptFunc", "Hello", "World");
In the javascript in the page hosting the silverlight have:-
function someJavascriptFunc(p1, p2)
{
alert(p1 + ' ' + p2);
}
Edit: Ken is right the above is the wrong way round.
Lets say you have this function in Silverlight:-
string GetStuff(string name)
{
return "Hello " + name;
}
You can now make this function available to javascript like this:-
HtmlPage.Window.SetProperty("sayHello", new Func<string, string>(GetStuff));
Now code in javascript can simply do something like this:-
alert(sayHello("Fred"));
If you're using events, in theory, you can use AttachEvent to subscribe to events. That's not quite the same thing as callbacks, but it's close.
Caveats: I haven't tested AttachEvent on Mozilla-based browsers (where the appropriate JS command is "addEventListener()" rather than "attachEvent()"), and I've had trouble getting AttachEvent() to work reliably even in IE. So I've always just used the [ScriptableMember] attribute, and called that from JS. Is there a reason you don't want to use that? (I'd be curious to hear if anyone has any better ideas.)
精彩评论