Using both APIs for flexibility

It's important to understand the difference between the declarative and native APIs, as any application will probably require the use of both. Using the declarative syntax is great for a concise description of the user interface, but runtime manipulation of the graphical elements will require a reference to one of the native widgets that this code wraps. To make this connection, each of the declarative types has an AssignTo field, which is typically passed a pointer to a var, which itself is a pointer to an object that represents a native type. This means that, during the user-interface-construction phase, the declarative API parser can create native widgets and set the pointer within your code for later use. Let's look at this feature in action:

package main

import (
"fmt"

"github.com/lxn/walk"
. "github.com/lxn/walk/declarative"
)

func main() {
var message *walk.Label
var userName *walk.TextEdit

MainWindow{
Title: "Hello",
Layout: VBox{},
Children: []Widget{
Label{
AssignTo: &message,
Text: "Hello World!",
},
TextEdit{
AssignTo: &userName,
OnTextChanged: func() {
welcome := fmt.Sprintf("Hello %s!", userName.Text())
message.SetText(welcome)
},
},
PushButton{
Text: "Quit",
OnClicked: func() {
walk.App().Exit(0)
},
},
},
}.Run()
}

The preceding code can be compiled exactly as the previous hello world examples (don't forget to include and process a manifest if you have created a new project for this sample). When running this example, you should see the following interface with an additional text input field. When you type into the input box, the welcome message will change, for example John Doe was entered for this screenshot:

The hello world with name entry

You will notice that the message and userName variables are not initialized directly by the application code, but by the time the function assigned to OnTextChanged is called, they hold valid references to instantiated widgets. Using this approach, we can get the type of access that the native API wrappers provide while also writing an easy-to-read UI definition provided by the declarative API.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.14.245