-
-
Notifications
You must be signed in to change notification settings - Fork 43
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create EventToCommand.Slider.ValueChanged.cs
- Loading branch information
Showing
1 changed file
with
66 additions
and
0 deletions.
There are no files selected for viewing
66 changes: 66 additions & 0 deletions
66
NuGet/RapidXaml.MAUI/EventToCommand/EventToCommand.Slider.ValueChanged.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,66 @@ | ||
using System.Windows.Input; | ||
|
||
namespace RapidXaml; | ||
|
||
public partial class EventToCommand : BindableObject | ||
{ | ||
public static ICommand GetValueChanged(BindableObject obj) | ||
=> (ICommand)obj.GetValue(ValueChangedProperty); | ||
|
||
public static void SetValueChanged(BindableObject obj, ICommand value) | ||
=> obj.SetValue(ValueChangedProperty, value); | ||
|
||
public static readonly BindableProperty ValueChangedProperty = | ||
BindableProperty.CreateAttached("ValueChanged", typeof(ICommand), typeof(EventToCommand), defaultValue: null, propertyChanged: OnValueChangedChanged); | ||
|
||
private static void OnValueChangedChanged(BindableObject bindable, object oldValue, object newValue) | ||
{ | ||
if (bindable is Slider sldr) | ||
{ | ||
if (oldValue is ICommand oldCmd) | ||
{ | ||
for (int i = sldr.Behaviors.Count; i >= 0; i--) | ||
{ | ||
if (sldr.Behaviors[i] is EventToCommandValueChangedBehavior oldBehavior && oldBehavior.CommandToInvoke == oldCmd) | ||
{ | ||
sldr.Behaviors.Remove(oldBehavior); | ||
break; | ||
} | ||
} | ||
} | ||
|
||
if (newValue is ICommand newCmd) | ||
{ | ||
sldr.Behaviors.Add(new EventToCommandValueChangedBehavior { CommandToInvoke = newCmd }); | ||
} | ||
} | ||
} | ||
|
||
internal partial class EventToCommandValueChangedBehavior : Behavior<Slider> | ||
{ | ||
public ICommand? CommandToInvoke { get; set; } | ||
|
||
protected override void OnAttachedTo(Slider sldr) | ||
{ | ||
sldr.ValueChanged += OnSliderValueChanged; | ||
base.OnAttachedTo(sldr); | ||
} | ||
|
||
protected override void OnDetachingFrom(Slider sldr) | ||
{ | ||
sldr.ValueChanged -= OnSliderValueChanged; | ||
base.OnDetachingFrom(sldr); | ||
} | ||
|
||
private void OnSliderValueChanged(object? sender, EventArgs e) | ||
{ | ||
if (this.CommandToInvoke != null) | ||
{ | ||
if (this.CommandToInvoke.CanExecute(null)) | ||
{ | ||
this.CommandToInvoke.Execute(null); | ||
} | ||
} | ||
} | ||
} | ||
} |