次の方法で共有


New WPF Features: Script Interop in Xbap

This is part of a series on New WPF Features

Often times you have Xbap hosted in a Html page and its pretty common to have some kind of interaction between the host and Xbap. In this release, we have enabled these scenarios.

Operation

Changes In

Code Sample

Invoking a function

Xbap

dynamic script = BrowserInteropHelper.HostScript;

              script.ReportProgress(progressValue.ToString());

Passing an object to a function

Script

function ReportDate(dateTime) {

    date = new Date(dateTime);

    var dateBox = document.getElementById("displayDate");

    dateBox.value = date.getFullYear();

}

Xbap

DateTime date1 = (DateTime)date.SelectedDate;

script.ReportDate(date1);

Fetching custom data from the script

Script

function ComplexData() {

    var res = { FirstName: "John", LastName:"Foo", Age:20 };

    return res;

}

Xbap

var result = script.ComplexData();

var resultName = result.FirstName;

var resultAge = result.Age;

tbData.Text = "FirstName: " + resultName + " Age: " + resultAge;

Fetch Function from the script

Script

function ReturnFunction() {

    return TestAdd;

}

function TestAdd(arg1, arg2) {

    return arg1 + arg2;

}

Xbap

var AddFunction = script.ReturnFunction();

var value = AddFunction.call(null, 5, 6);

tbData1.Text = "Total: " + value;

Setting up a default callback

Script

function SetClickHandler(handler) {

    btn1.onclick = handler;

}

Xbap

OnClickHandler handler1 = new OnClickHandler();

script.SetClickHandler(handler1);

[ComVisible(true)]

    public class OnClickHandler

    {

        [DispId(0)] // This makes it the object’s default member.

        public void Invoke()

        {

            MessageBox.Show("Default Invoke");

        }

}

Setting up a custom callback

Script

var XBAPCallback;

function SetCallback(callbackObj) {

    XBAPCallback = callbackObj;

    btn2.onclick = OnViewReportButtonClick;

}

function OnViewReportButtonClick() {

    date = new Date();

    XBAPCallback.Callback(date.getFullYear());

}

Xbap

OnClickHandler handler = new OnClickHandler();

handler.mainViewModel = this.DataContext;

script.SetCallback(handler);

[ComVisible(true)]

    public class OnClickHandler

    {

        public object mainViewModel;

  public void Callback(object arg)

        {

            ((MainViewModel)mainViewModel).MyText = "CallBack:" + arg.ToString();

        }

    };

A simple sample (love the simple part..) is attached to show the above in action.. Note that you'll need to enable scripts in the browser to get the sample working.

Also, you could look at the publish folder in order to play with the sample without building it.

Share this post

 

scriptInteropXbap.zip

Comments

  • Anonymous
    November 03, 2009
    This series is awesome, thanks for posting!