Articles in this section

How to get the selected date in Xamarin.Forms SfPicker

The Xamarin.Forms SfPicker allows to get current selected date using the SelectedItem property. In the selection changed event, use the selected item property to get the current selected Xamarin.Forms SfPicker item. This article explains how to get the selected items in Xamarin.Forms SfPicker and bind value to the label text property.

 

The following steps explain how to get the selected date in Xamarin.Forms SfPicker.

 

Step 1: Create symbol view model class and declare the properties.

Step 2: Create a simple class, which should be inherited from SfPicker to add the date picker in Xamarin.Forms SfPicker. For more details about adding date picker to Xamarin.Forms SfPicker, refer to the sample.

Step 3 : Add that class in XAML page and set the properties that needs to be assigned.

 

The following code sample demonstrates how to add Xamarin.Forms SfPicker in XAML page.

XAML:

<ContentPage.BindingContext>
        <local:DateTimeViewModel  x:Name="dateTimeModel"/>
 </ContentPage.BindingContext>    
 
<ContentPage.Content>
        
        <StackLayout>
            
            <local:DateTimePicker x:Name="picker" PickerHeight="400" PickerWidth="300" ColumnHeaderHeight="50" SelectionChanged="Picker_SelectionChanged">
            </local:DateTimePicker>
 
            <Label Text="{Binding SelectedDate}"  VerticalTextAlignment="Center" BackgroundColor="Green" HeightRequest="75"/>
            
        </StackLayout>
 
  </ContentPage.Content>
 

 

Step 4: Hook the SelectionChanged event in Xamarin.Forms SfPicker. By hooking this event, you can get the current selected item in Xamarin.Forms SfPicker.

 

The following code sample demonstrates how to get the selected item in Xamarin.Forms SfPicker.

 

C#:

private void Picker_SelectionChanged(object sender, SelectionChangedEventArgs e)
{       
            var selectedItem = picker.SelectedItem as ObservableCollection<object>;        
 
            string month = selectedItem[0].ToString();
            string day = selectedItem[1].ToString();
            string year = selectedItem[2].ToString();
 
            dateTimeModel.SelectedDate = "Month : " + month + "\t\tDay : " + day + " \t\tYear : " + year;
  }

 

 

Output:

Get selected date in Xamarin.Forms SfPicker

 

You can find the sample in the following link: Sample

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Access denied
Access denied