how to save a listview record on the switch button on then save on server

mukeshmukesh Member ✭✭

how to save a list base on the switch button on the selected true with at list one row selection compulsory.

Answers

  • LandLuLandLu Member, Xamarin Team Xamurai

    If you used view model to construct your list view, the switch's toggling operation will notify the view model. Then when the user clicks the submit button, you could upload the list view's items source directly.
    XAML could be:

    <ListView ItemsSource="{Binding ListViewSource}">
        <ListView.ItemTemplate>
            <DataTemplate>
                <ViewCell>
                    <StackLayout Orientation="Horizontal">
                        <Label HorizontalOptions="StartAndExpand" Text="{Binding Text}"/>
                        <Switch HorizontalOptions="End" IsToggled="{Binding IsToggled}"/>
                    </StackLayout>
                </ViewCell>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
    

    Code behind:

    public partial class MainPage : ContentPage
    {        
        public MainPage()
        {
            InitializeComponent();
    
            BindingContext = new MainPageViewModel();
        }
    }
    
    public class MainPageViewModel
    {      
        public List<MainPageModel> ListViewSource { set; get; }
    
        // ... submit command
    }
    
    public class MainPageModel : INotifyPropertyChanged
    {
        string text;
        public string Text
        {
            set
            {
                text = value;
                onPropertyChanged();
            }
            get
            {
                return text;
            }
        }
    
        // When the switch's value changed, this property will be changed too
        bool isToggled;
        public bool IsToggled
        {
            set
            {
                isToggled = value;
                onPropertyChanged();
            }
            get
            {
                return isToggled;
            }
        }
    
        public event PropertyChangedEventHandler PropertyChanged;
        void onPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
    
Sign In or Register to comment.