Reputation: 3563
Just wanted to confirm whether DatePicker
's DateSelected
is not Binding
possible like:
DateSelected="{Binding TargetDateSelectedCommand}"/>
To me it looks like handler
has to be created in .cs
file.
Upvotes: 0
Views: 549
Reputation: 12723
It is possible, you could have a try with Turn Events into Commands with Behaviors.
Custom a Behavior<DatePicker>
class as follows:
public class DatePickerSelectedItemBehavior: Behavior<DatePicker>
{
public static readonly BindableProperty CommandProperty =
BindableProperty.Create("Command", typeof(ICommand), typeof(DatePickerSelectedItemBehavior), null);
public static readonly BindableProperty InputConverterProperty =
BindableProperty.Create("Converter", typeof(IValueConverter), typeof(DatePickerSelectedItemBehavior), null);
public ICommand Command
{
get { return (ICommand)GetValue(CommandProperty); }
set { SetValue(CommandProperty, value); }
}
public IValueConverter Converter
{
get { return (IValueConverter)GetValue(InputConverterProperty); }
set { SetValue(InputConverterProperty, value); }
}
public DatePicker AssociatedObject { get; private set; }
protected override void OnAttachedTo(DatePicker bindable)
{
base.OnAttachedTo(bindable);
AssociatedObject = bindable;
bindable.BindingContextChanged += OnBindingContextChanged;
bindable.DateSelected += DatePickerItemSelected;
}
protected override void OnDetachingFrom(DatePicker bindable)
{
base.OnDetachingFrom(bindable);
bindable.BindingContextChanged -= OnBindingContextChanged;
bindable.DateSelected -= DatePickerItemSelected;
AssociatedObject = null;
}
void OnBindingContextChanged(object sender, EventArgs e)
{
OnBindingContextChanged();
}
void DatePickerItemSelected(object sender, DateChangedEventArgs e)
{
if (Command == null)
{
return;
}
object parameter = Converter.Convert(e, typeof(object), null, null);
if (Command.CanExecute(parameter))
{
Command.Execute(parameter);
}
}
protected override void OnBindingContextChanged()
{
base.OnBindingContextChanged();
BindingContext = AssociatedObject.BindingContext;
}
}
Then used in Xaml:
<ContentPage.Resources>
<ResourceDictionary>
<local:SelectedItemEventArgsToSelectedItemConverter x:Key="SelectedItemConverter" />
</ResourceDictionary>
</ContentPage.Resources>
...
<DatePicker >
<DatePicker.Behaviors>
<local:DatePickerSelectedItemBehavior Command="{Binding OutputAgeCommand}"
Converter="{StaticResource SelectedItemConverter}" />
</DatePicker.Behaviors>
</DatePicker>
Here is the SelectedItemEventArgsToSelectedItemConverter.cs:
public class SelectedItemEventArgsToSelectedItemConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var eventArgs = value as DateChangedEventArgs;
return eventArgs.NewDate;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
Upvotes: 2