问题
I wonder if there is a way to create a runtime component (written in C# for example) which allows working with UI elements from different environments.
For example I would like to append an UI element such as MediaElement
to a given Panel
(C#) or div
(Javascript).
Can I call a method in a runtime component like this: cmpt.setPlayer((Panel) playerParent);
(C#) and cmpt.setPlayer(getElementByClass('.playerParent'));
(Javascript).
Is this possible somehow?
If not (and I would totally understand that), is there a way to create one runtime component which offers let's say two ways of declaring a function, one for being called from C# and one for Javascript?
回答1:
It's not actually possible to share UI elements between the HTML/CSS rendering engine (the JS app) and a C#/C++ component. The C# code won't have the underlying runtime that understands an HTML element object. Similarly, a UIElement from XAML won't make any sense to the HTML/CSS engine in the JS app. In short, UI elements can't be shared across that boundary, and thus Windows Runtime Components are intended for non-UI functionality.
To your second question, components aren't structured to do what your suggest, i.e. having separate C# and JS methods, because you can't implement a component in JavaScript to begin with. The idea is that a method written in C# or C++ is projected into JavaScript by the runtime, but it's still implemented in those languages.
Folks who develop UI-related libraries for Windows Store apps generally implement separate versions for C#/C++ and for JS, because of these differences. Of course, non-UI stuff can go into its own WinRT component, and I think that you can have a JS library append stuff to a namespace coming from the component, because the latter is projected into JS as a JS object like any other. This kind of hybrid approach would keep your API surface area in one namespace, even though it has a mixed implementation. I haven't tried this though.
An alternate approach might be to have the WinRT component use various callbacks to instruct the host app to perform UI tasks, which would necessarily include creation of UI elements. The component could manage the parameters and underlying data model, that is, and use those callbacks to trigger the UI work accordingly.
It's worth mentioning that I did a rather exhaustive treatment of WinRT components, including async, in Chapter 18 my free ebook, Programming Windows Store Apps with HTML, CSS, and JavaScript, 2nd Edition.
来源:https://stackoverflow.com/questions/28323208/passing-ui-elements-to-and-from-windows-runtime-component-in-different-environme