using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using SharedGui.ViewModel; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace SharedGui.View { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class BarLevelInputView : ContentView { private BarLevelInputViewModel _LocalViewModel; public BarLevelInputView() { InitializeComponent(); _LocalViewModel = new BarLevelInputViewModel(); _LocalViewModel.PropertyChanged += (sender, args) => { // Update Current property from view model on user input. if (args.PropertyName != nameof(BarLevelInputViewModel.Current)) return; var viewModel = sender as BarLevelInputViewModel; Current = viewModel?.Current != null ? viewModel.Current.Value.ToString() : String.Empty; }; // Do not bind entire control to local view model. Doing this would break binding of BatteryView control. this.BarLevelElement.BindingContext = _LocalViewModel; this.BarLevelStepper.BindingContext = _LocalViewModel; } /// /// Create bindable property to to allow "Maximum"- proptery to act as a valid target for data binding. /// public static readonly BindableProperty MaximumProperty = BindableProperty.Create( "Maximum", typeof(string), typeof(BarLevelInputView), "7", propertyChanged: OnMaximumChanged); /// /// Holds the count of bars wich represent charing level full. /// public string Maximum { get => (string)GetValue(MaximumProperty); set => SetValue(MaximumProperty, value); } /// /// Notifies when value changes. Is required to make binding work. /// static void OnMaximumChanged(BindableObject bindable, object oldValue, object newValue) { if (newValue != oldValue) { var batteryView = bindable as BarLevelInputView; batteryView?.SetMaximum(int.TryParse(newValue.ToString(), out int maximum) ? (int?)maximum : null); } } public void SetMaximum(int? maximum) => _LocalViewModel.Maximum = maximum; /// /// Create bindable property to to allow "Current"- proptery to act as a valid target for data binding. /// public static readonly BindableProperty CurrentProperty = BindableProperty.Create( "Current", typeof(string), typeof(BarLevelInputView), "7", BindingMode.TwoWay, propertyChanged: OnCurrentChanged); /// /// Holds the count of bars wich represent the current charing level. /// public string Current { get => (string)GetValue(CurrentProperty); set => SetValue(CurrentProperty, value); } /// /// Notifies when value changes. Is required to make binding work. /// static void OnCurrentChanged(BindableObject bindable, object oldValue, object newValue) { if (newValue != oldValue) { var batteryView = bindable as BarLevelInputView; int current; batteryView?.SetCurrent(int.TryParse(newValue.ToString(), out current) ? (int?)current : null); } } public void SetCurrent(int? current) => _LocalViewModel.Current = current; } }