什么是hostComponent?

Art*_*mix 1 apache-flex skin actionscript-3 flex-spark

我在Flex中为progressBar换肤,在阅读了一下之后,我看到有一个叫做hostComponent的东西.

Adobe网站说:

"The host component is the component that uses the skin. By specifying the host component, Spark skins can gain a reference to the component instance that uses the skin by using the hostComponent property."
Run Code Online (Sandbox Code Playgroud)

但是,我仍然不明白这是如何运作的.

有任何快速实用的解释吗?

谢谢!

RIA*_*tar 8

在Spark体系结构中创建自定义组件时,通常将它们分成两部分:

  • 一个ActionScript类,包含自定义组件的核心功能.该类通常会扩展SkinnableComponent或SkinnableContainer
  • MXML外观类,与ActionScript类松散关联,仅包含组件的可视化表示.这个类不应该包含任何真正的功能,用另一个皮肤替换它应该是微不足道的.

从皮肤的角度来看,这两个类中的第一个被称为主机组件.

一个简单的例子

让我们通过扩展SkinnableContainer来创建一个非常简单的面板:

public class MyPanel extends SkinnableContainer {

    [Bindable]
    public var title:String;

}
Run Code Online (Sandbox Code Playgroud)

正如你所看到的,我创建了一个属性'title',我们想用它来在Panel中显示一个标题.现在让我们创建一个使用此属性的外观:

<?xml version="1.0" encoding="utf-8"?>
<s:Skin xmlns:fx="http://ns.adobe.com/mxml/2009"
        xmlns:s="library://ns.adobe.com/flex/spark">

    <fx:Metadata>
        [HostComponent("path.to.MyPanel")]
    </fx:Metadata>

    <!-- graphics for title bar go here -->
    <s:Label text="{hostComponent.title}" top="5" left="5" />

    <!-- graphics for panel content go here -->
    <s:Group id="contentGroup" top="30" bottom="0" left="0" right="0" />

</s:Skin>
Run Code Online (Sandbox Code Playgroud)

hostcomponent在'metadata'块中定义,您可以看到我们可以使用它将其属性绑定到我们的可视化表示中.'contentGroup'就在那里,因为SkinnableContainer需要它; 这就是你放入自定义面板的所有元素.所以这是如何使用它:

<myComps:MyPanel title="Panel title" skinClass="path.to.skins.MyPanelSkin">
    <s:Label text="Hello Panel" />
    <!--everything in here goes into the 'contentGroup'-->
</myComps:MyPanel>
Run Code Online (Sandbox Code Playgroud)