Hi!
I created a SetStateBehavior for new feature - VisualStateManager. I set binding beetwen Behavior and ViewModel, but BindableProperty in my Behavior does't update. I checked, and if i setting binding to my ViewModel property without behavior, then all works, but in Behavior doesn't.
This property is State
Behavior:
public class SetStateBehavior : BindableBehavior<View>
{
// ===== Bindable Properties =====
public static readonly BindableProperty StateProperty = BindableProperty.Create(
"State",
typeof(string),
typeof(SetStateBehavior),
null);
public string State
{
get => (string) GetValue(StateProperty);
set
{
SetState(value);
SetValue(StateProperty, value);
}
}
// ===== Private Fields =====
private View _element;
// ===== Override Methods =====
protected override void OnAttachedTo(View bindable)
{
base.OnAttachedTo(bindable);
_element = bindable;
}
protected override void OnDetachingFrom(View bindable)
{
_element = null;
base.OnDetachingFrom(bindable);
}
// ===== Private Methods =====
private void SetState(string state)
{
State = state;
VisualStateManager.GoToState(_element, state);
}
}
BindableBehavior:
public class BindableBehavior : Behavior where T : BindableObject
{
public T AssociatedObject { get; private set; }
protected override void OnAttachedTo(T visualElement)
{
base.OnAttachedTo(visualElement);
AssociatedObject = visualElement;
if (visualElement.BindingContext != null)
BindingContext = visualElement.BindingContext;
visualElement.BindingContextChanged += OnBindingContextChanged;
}
private void OnBindingContextChanged(object sender, EventArgs e)
{
OnBindingContextChanged();
}
protected override void OnDetachingFrom(T view)
{
view.BindingContextChanged -= OnBindingContextChanged;
}
protected override void OnBindingContextChanged()
{
base.OnBindingContextChanged();
BindingContext = AssociatedObject.BindingContext;
}
}
Xaml:
<Entry.Behaviors>
<behaviors:SetStateBehavior State="{Binding Password.State}"/>
<behaviors:EventToCommandBehavior EventName="TextChanged"
Command="{Binding ValidatePasswordCommand}"/>
</Entry.Behaviors>
</Entry>
Tagged: xamarin.forms behaviors bindings xaml