AdSense

網頁

2018/6/17

ZK <selectbox>下拉選單value text

ZK <selectbox>下拉選單搭配value text的MVVM做法如下。


<selectbox>要搭配<temploate>使用。屬性selectedItem用來綁定選取項目的bind物件。

index.zul

<zk>
<window apply="org.zkoss.bind.BindComposer"
    viewModel="@id('vm')@init('idv.matt.vm.MyVM')">
    <selectbox model="@load(vm.departmentList)" 
               selectedItem="@bind(vm.selectedDepartment)"
        onSelect="@command('select')">
        <template name="model">
            <label value="${each.text}"/>
        </template>
    </selectbox>
</window>

對映的ViewModel

MyVM.java

package idv.matt.vm;

import java.util.ArrayList;
import java.util.List;

import org.zkoss.bind.annotation.Command;
import org.zkoss.bind.annotation.ContextParam;
import org.zkoss.bind.annotation.Init;

import idv.matt.vm.ui.ValueText;

public class MyVM {
    
    private ValueText selectedDepartment;
    private List<ValueText> departmentList = new ArrayList<ValueText>();
     
    @Init
    public void init() {
        // 選單內容
        ValueText vt1 = new ValueText("hr","HR");
        ValueText vt2 = new ValueText("mk","Marketing");
        ValueText vt3 = new ValueText("pd","Production");
        ValueText vt4 = new ValueText("ss","Sales");
        ValueText vt5 = new ValueText("fn","Financial ");
        departmentList.add(vt1);
        departmentList.add(vt2);
        departmentList.add(vt3);
        departmentList.add(vt4);
        departmentList.add(vt5);
        
        selectedDepartment = vt3; // 預設的選單內容
        
    }
    
    @Command
    public void select() {
        
        System.out.println(selectedDepartment.getValue()); // value
        System.out.println(selectedDepartment.getText()); // text
        
    }

    public ValueText getSelectedDepartment() {
        return selectedDepartment;
    }

    public void setSelectedDepartment(ValueText selectedDepartment) {
        this.selectedDepartment = selectedDepartment;
    }

    public List<ValueText> getDepartmentList() {
        return departmentList;
    }

    public void setDepartmentList(List<ValueText> departmentList) {
        this.departmentList = departmentList;
    }
    
}

用來裝載選單value text內容的類別。

ValueText.java

package idv.matt.vm.ui;

public class ValueText {
    private String value;
    private String text;
    
    public ValueText(String value, String text) {
      this.value=value;
      this.text=text;
    }
    
    public String getText() {
      return this.text;
    }
    
    public String getValue() {
      return this.value;
    }
}


沒有留言:

AdSense