Skip to main content
Home Forums Silverlight Programming Programming with JavaScript Raising events from javascript against silverlight controls
2 replies. Latest Post by Gonyoda on June 19, 2009.
(0)
Gonyoda
Member
0 points
2 Posts
06-17-2009 9:33 PM |
I want to raise an event, like OnClick, from the client Javascript.
I've got a silverlight control hosted on a web page that has a button on it, and the button has an onclick event handler. From the javascript, I want to fire the event:
partial xaml:<Button Click="okButton_Click" x:Name="okButton" Width="75" Height="25" HorizontalAlignment="Left" Content="OK"></Button>
java script code:function clickOKButton() { var slv = document.getElementById('Xaml'); var button = xaml.content.root.findName("okButton"); // now what? // I've tried: // button.onclick() // button.click()
}
I know I could "simulate" the onclick by using a [ScriptableMember()] member function in the code-behind, but I'd prefer to avoid having to do that. I'm attempting to test a fairly large silverlight application using Selenium/Silvernium and so far I can get pretty far by setting/getting various properties of the button (or other) controls. But I'm stuck right now since I can't seem to fire any events to mimic user actions against the silverlight app.
Thanks for any help!
-John
ksleung
Contributor
5366 points
1,028 Posts
06-17-2009 9:59 PM |
Unfortunately you cannot trigger "real" button events. A lot of Silverlight operations -- saving files, opening files, increase isolated storage quota, etc -- must be triggered by a user event, and there is no way to go around it (believe me, a lot of people have tried to no avail ). If you can't achieve this inside Silverlight, I doubt you can do it from outside Silverlight (namely Javascript). Of course, I'm not saying it is completely impossible... just not from Silverlight, and not by calling Silverlight from Javascript.
06-19-2009 8:59 AM |
I figured out how to raise the OnClick() event of a button control.
1) Create a new Silverlight class library with a class that inherits from Button:
[ScriptableType]public class MyButton : Button{ public void DoClick() { OnClick(); }}
2) Change the XAML to use the new class instead of a button (add a reference to your class library first)
<
<My:MyButton Content="DoSomething" Click="doSomething_Click" x:Name="btnDoIt"></My:MyButton>
3) Add a FindControl() function to your code that returns a MyButton object:
[
4) In javascript (or, better yet, Silvernium) access the control with javascript that looks like this to fire the click event:
document.getElementById('MySilverlightControlName').content.MyUserControl.FindControl("btnDoIt").DoClick();
Presto! You just fired the click event of the button. This works even with buttons bound to command objects instead of Click events. I'm sure that pretty much any protected member (event, prop, etc) of Button can be exposed this way. I'm also sure it can be used to expose methods for other Silverlight controls.