Skip to content

Instantly share code, notes, and snippets.

@julesx
Last active October 20, 2017 16:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save julesx/c2b3a23eceaf9c80084007ff5306af8c to your computer and use it in GitHub Desktop.
Save julesx/c2b3a23eceaf9c80084007ff5306af8c to your computer and use it in GitHub Desktop.
public class VisualElementLostFocusBehavior : Behavior<VisualElement>
{
public static readonly BindableProperty CommandProperty =
BindableProperty.Create("Command", typeof(ICommand), typeof(VisualElementLostFocusBehavior));
public ICommand Command
{
get { return (ICommand)GetValue(CommandProperty); }
set { SetValue(CommandProperty, value); }
}
private VisualElement _bindable;
protected override void OnAttachedTo(VisualElement bindable)
{
base.OnAttachedTo(bindable);
_bindable = bindable;
bindable.BindingContextChanged += BindableOnBindingContextChanged;
bindable.Unfocused += BindableOnUnfocused;
bindable.Focused += BindableFocused;
}
private void BindableFocused(object sender, FocusEventArgs e)
{
var visualElement = (VisualElement)sender;
var vm = (IItemFieldVm)visualElement.BindingContext;
//Debug.WriteLine("FOCUSED ------------" + " - " + vm.Header + " - " + vm.FieldValue + " - " + vm.DisplayType);
}
private void BindableOnBindingContextChanged(object sender, EventArgs eventArgs)
{
this.BindingContext = _bindable.BindingContext;
}
private void BindableOnUnfocused(object sender, FocusEventArgs focusEventArgs)
{
var visualElement = (VisualElement) sender;
var vm = (IItemFieldVm)visualElement.BindingContext;
//Debug.WriteLine("UNFOCUSED ------------" + " - " + vm.Header + " - " + vm.FieldValue + " - " + vm.DisplayType);
Command?.Execute(null);
}
protected override void OnDetachingFrom(VisualElement bindable)
{
base.OnDetachingFrom(bindable);
bindable.BindingContextChanged -= BindableOnBindingContextChanged;
bindable.Unfocused -= BindableOnUnfocused;
_bindable = null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment