vs2010 学习Silverlight学习笔记(19):JS调用SL
概要:
上篇在SL中调用JS的感觉自己学习的很差,关于JS用的也很简单。这篇是关于在JS中调用.net代码的。
内容:
ScriptableMemberAttribute:允许我们在Silverlight把成员暴露给 Script。
ScriptableTypeAttribute:允许我们在Silverlight把类型暴露给Script。
[ScriptableMember]//将方法暴漏给js
public void Add(int x, int y)
{
int z = x + y;
this.result.Text = String.Format("{0} + {1} = {2}", x, y, z);
}
[ScriptableType]//将类成员暴漏给js
public class Calculator
{
[ScriptableMember]
public int Add(int x, int y)
{
return x + y;
}
}
使用RegisterScriptableObject
并在加载时注册一个脚本可调用的当前页面实 例:
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
HtmlPage.RegisterScriptableObject("Calculator", this);
}
[ScriptableMember]
public void Add(int x, int y)
{
int z = x + y;
this.result.Text = String.Format("{0} + {1} = {2}", x, y, z);
}
Js文件:
<script type="text/javascript">
function callSilverlight()
{
var slPlugin = $get('Xaml1');
slPlugin.content.Calculator.Add($get('txt1').value,$get('txt2').value);
}
</script>
Html代码:
<div class="main">
<input id="txt1" type="text" />
<input id="txt2" type="text" />
<input id="Button1" type="button" value="确 定" onclick="callSilverlight()"
/>
</div>
使用RegisterCreateableType
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
HtmlPage.RegisterCreateableType("calculator", typeof(Calculator));
}
[ScriptableType]
public class Calculator
{
[ScriptableMember]
public int Add(int x, int y)
{
return x + y;
}
}
<script type="text/javascript">
function callSilverlight()
{
var slPlugin = $get('Xaml1');
var cal = slPlugin.content.services.createObject("calculator");
alert(cal.Add($get('txt1').value,$get('txt2').value));
}
</script>