请参阅下面的完整示例。主要部分是 ViewModel(VM) 和 ViewModelLoader(VML)。VM 是您希望在 UI 中显示的内容。VML 用来自数据库的数据填充 VM。使用 PropertyModel 我绑定下拉项和选定的值。为了更新 doropdown,我正在更新 VM 并将组件添加到 AjaxRequestTarget。
public class PlayingWithDropDownPage extends WebPage {
public PlayingWithDropDownPage() {
final ViewModelLoader viewModelLoader = new ViewModelLoader();
final ViewModel viewModel = viewModelLoader.load();
IChoiceRenderer choiceRenderer = new ChoiceRenderer("name", "id");
final DropDownChoice dropDownChoice = new DropDownChoice("dropDown");
dropDownChoice.setChoiceRenderer(choiceRenderer);
dropDownChoice.setChoices(viewModel.getItemsModel());
dropDownChoice.setModel(viewModel.getSelectedModel());
dropDownChoice.add(new AjaxFormComponentUpdatingBehavior("onchange") {
@Override
protected void onUpdate(AjaxRequestTarget target) {
viewModelLoader.load(viewModel);
target.add(dropDownChoice);
}
});
add(dropDownChoice);
}
public static class ViewModel implements Serializable {
private WhatToShow whatToShow;
private List<Item> items = new ArrayList<>();
private Item selected;
public IModel<List<Item>> getItemsModel() {
return new PropertyModel<>(this, "items");
}
public IModel<Item> getSelectedModel() {
return new PropertyModel<>(this, "selected");
}
}
public static class ViewModelLoader extends LoadableDetachableModel<ViewModel> {
@Override
protected ViewModel load() {
return load(new ViewModel());
}
protected ViewModel load(ViewModel vm) {
vm.items.clear();
if (vm.whatToShow == WhatToShow.City) {
vm.whatToShow = WhatToShow.Person;
vm.items.add(new Person("1", "John", "Smith"));
vm.items.add(new Person("2", "Robert", "Evans"));
vm.items.add(new Person("3", "Jeff", "Jones"));
} else {
vm.whatToShow = WhatToShow.City;
vm.items.add(new City("1", "London"));
vm.items.add(new City("2", "Moscow"));
vm.items.add(new City("3", "Kiev"));
}
return vm;
}
}
public static interface Item {
public String getId();
public String getName();
}
private enum WhatToShow {
Person,
City
}
public static class City implements Item {
public String id;
public String name;
public City(String id, String name) {
this.id = id;
this.name = name;
}
@Override
public String getId() {
return id;
}
@Override
public String getName() {
return name;
}
}
public static class Person implements Item {
public String id;
public String fname;
public String lname;
public Person(String id, String fname, String lname) {
this.id = id;
this.fname = fname;
this.lname = lname;
}
@Override
public String getId() {
return id;
}
@Override
public String getName() {
return String.format("%s %s", fname, lname);
}
}
}