Skip to content

Commit

Permalink
Add ability to use data binding to drive disable state of a widget.
Browse files Browse the repository at this point in the history
  • Loading branch information
Cedric BAIL committed May 14, 2023
1 parent 991a6d4 commit 1ac2327
Showing 1 changed file with 65 additions and 0 deletions.
65 changes: 65 additions & 0 deletions widget/widget.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (

"fyne.io/fyne/v2"
"fyne.io/fyne/v2/canvas"
"fyne.io/fyne/v2/data/binding"
"fyne.io/fyne/v2/internal/cache"
internalWidget "fyne.io/fyne/v2/internal/widget"
)
Expand Down Expand Up @@ -166,6 +167,9 @@ func (w *BaseWidget) super() fyne.Widget {
type DisableableWidget struct {
BaseWidget

disableListener binding.DataListener
disableBinding binding.Bool

disabled bool
}

Expand Down Expand Up @@ -199,6 +203,67 @@ func (w *DisableableWidget) Disabled() bool {
return w.disabled
}

// UnbindDisable remove the previously bound binding.Bool that manage the disable state of the widget
//
// Since 2.4
func (w *DisableableWidget) UnbindDisable() {
w.propertyLock.RLock()
defer w.propertyLock.RUnlock()

if w.disableListener == nil {
return
}
w.disableBinding.RemoveListener(w.disableListener)
w.disableListener = nil
w.disableBinding = nil
}

// BindDisable will use the passed binding.Bool to manage the disable state of the widget
//
// Since 2.4
func (w *DisableableWidget) BindDisable(data binding.Bool) {
w.propertyLock.RLock()
defer w.propertyLock.RUnlock()

getBool := func(data binding.Bool) bool {
v, err := data.Get()
if err != nil {
return false
}
return v
}

applyDisable := func(disable bool) {
if disable {
w.Disable()
} else {
w.Enable()
}
}

if w.disableBinding == data {
goto refreshDisable
}
if w.disableListener != nil {
w.UnbindDisable()
}

w.disableListener = binding.NewDataListener(func() {
isDisable := w.Disabled()
disable := getBool(data)
if isDisable == disable {
return
}
applyDisable(disable)
})
w.disableBinding = data
w.disableBinding.AddListener(w.disableListener)

refreshDisable:
disable := getBool(data)
applyDisable(disable)
}

// NewSimpleRenderer creates a new SimpleRenderer to render a widget using a
// single fyne.CanvasObject.
//
Expand Down

0 comments on commit 1ac2327

Please sign in to comment.