0
votes

I have a picker control which is optional field and the user can set the selected item of picker to be empty if he wants.

Is it possible to have Select as the additional option in itemsource of xamarin forms picker control.

Code for Custom picker:

    <controls:CustomPicker
                        Grid.Row="1"
                        Grid.Column="1"
                        Margin="0,5,0,0"
                        Image="Downarrow"
                        ItemDisplayBinding="{Binding abb}"
                        ItemsSource="{Binding StateList}"
                        Placeholder="Select"
                        SelectedIndex="{Binding StateSelectedIndex}"
                        Style="{StaticResource Key=PickerHeight}" />

     StateSelectedIndex = -1;

I tried setting selected index = -1. That works only when nothing is selected in the picker control, but once if an item is selected from the picker, then option "Select" can not be chosen (disappears).

I tried referring below url Default value for Picker but this did not help.

Any help is appreciated.

1
Could you post the full code in code behind and CustomPicker ?Lucas Zhang

1 Answers

1
votes

Solution 1: You should set the binding mode of SelectedIndex

SelectedIndex="{Binding StateSelectedIndex,Mode=TwoWay}"

Solution 2:

You could binding the value of SelectedItem in ViewModel .

public class YourViewModel: INotifyPropertyChanged
    public event PropertyChangedEventHandler PropertyChanged;
    private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    public ObservableCollection<string> MyItems { get; set; }

    private string selectItem;
    public string SelectItem
    {
        get
        {
            return selectItem;
        }

        set
        {
            if(value!=null)
            {
                selectItem = value;
                NotifyPropertyChanged("SelectItem");


                int SelectIndex = MyItems.IndexOf(value);

               // this will been invoked when user change the select , do some thing you want

            }
        }
    }