How to enable switch on multi-select listview with binding in Xamarin.Forms?

别来无恙 提交于 2019-12-25 01:58:57

问题


I found this article/sample code it is how to make a to-do list. If you browse the code it is using bindings to determine if the task is done or not. What I am trying to accomplish is the same concept as the to-do list.

Please visit my Github Repository for my full code:

Here is my app logic:

  1. Upon loading of the application the app will show all the list of activities (e.g. Walking, climbing, rafting, etc.).
  2. The user will select 1 or more activities.
  3. The user will save the form in the local database.
  4. If the user wants to remove or update an activity they have chosen the user will go to the list of forms they have submitted and when the user chose what form the want to update the user will be redirected to the list of activities with the switch of the activities they have chosen (meaning the activities stored in the activities selected table) enabled.

Basically like a to-do list. When the user checked what activities have already done the state will be checked or not. I don't have much knowledge in bindings I am having a hard time to implement it on my application.

Here is my XAML Code:

<ListView SeparatorVisibility="None" x:Name="lstActivity" ItemSelected="lstActivity_ItemSelected" HasUnevenRows="True">
  <ListView.ItemTemplate>
       <DataTemplate>
            <ViewCell>
                <Frame StyleClass="lstframe" CornerRadius="0" BorderColor="Transparent" HasShadow="False">
                     <StackLayout StyleClass="lstContainer" VerticalOptions="CenterAndExpand">
                          <Grid>
                             <Label StyleClass="lstActivityName" VerticalOptions="Center" Grid.Row="0" Grid.Column="0" Text="{Binding ActivityDescription}">
                                  <Label.FontFamily>
                                        <OnPlatform x:TypeArguments="x:String">
                                             <On Platform="Android" Value="Poppins-Regular.otf#Poppins-Regular"/>
                                        </OnPlatform>
                                   </Label.FontFamily>
                             </Label>
                             <Switch Grid.Row="0" Grid.Column="1" IsToggled="{Binding Selected}" />
                           </Grid>
                      </StackLayout>
                 </Frame>
             </ViewCell>
       </DataTemplate>
  </ListView.ItemTemplate>

Here is how I list all the activities without enabled state:

var db = DependencyService.Get<ISQLiteDB>();
var conn = db.GetConnection();

var getActivity = conn.QueryAsync<ActivityTable>("SELECT * FROM tblActivity WHERE Deleted != '1' ORDER BY ActivityDescription");
var resultCount = getActivity.Result.Count;

if (resultCount > 0)
{
   result = getActivity.Result;
   lstActivity.ItemsSource = result;

   lstActivity.IsVisible = true;
}
else
{
    lstActivity.IsVisible = false;
}

Here is my ActivityTable Class (Here is where I store the list of the activity):

namespace TBSApp.Data
{
    [Table("tblActivity")]
    public class ActivityTable
    {
        [PrimaryKey]
        public string ActivityID { get; set; }
        public string ActivityDescription { get; set; }
        public string RecordLog { get; set; }
        public DateTime LastSync { get; set; }
        public DateTime LastUpdated { get; set; }
        public int Deleted { get; set; }
        public int Checked { get; set; }
        public bool Selected { get; set; }
    }
}

Here is my CAFActivityTable (Where I store the selected activity):

[Table("tblCAFActivity")]
public class CAFActivityTable
{
    public string CAFNo { get; set; }
    public string ActivityID { get; set; }
    public DateTime LastSync { get; set; }
    public DateTime LastUpdated { get; set; }
    public int Deleted { get; set; }
    public int Checked { get; set; }
}

回答1:


It seems you have bound the Switch's IsToggled to your model's Selected. So your ActivityTable model should contain a bool value Selected property:

public class ActivityTable : INotifyPropertyChanged
{
    string activityDescription;
    public string ActivityDescription
    {
        get => activityDescription;
        set
        {
            if (activityDescription != value)
            {
                activityDescription = value;
                onPropertyChanged();
            }
        }
    }

    bool selected;
    public bool Selected
    {
        get => selected;
        set
        {
            if (selected != value)
            {
                selected = value;
                onPropertyChanged();
            }
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    void onPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

You could change the switch's state through Selected after implementing the INotifyPropertyChanged interface.

Update:

Compare the elements in ActivityTable to the items in CAFActivityTable. When you find the item has the same ActivityID, change the current item's selected state:

var activityItems = await ActivityConnection.Table<ActivityTable>().ToListAsync();
var CAFItems = await CafConnection.Table<CAFActivityTable>().ToListAsync();

foreach (var item in activityItems)
{
    foreach (var CAFItem in CAFItems)
    {
        if (item.ActivityID == CAFItem.ActivityID)
        {
            item.Selected = true;
            break;
        }
    }
}
// Bind your list view's items source to this activityItems
// If you want to update the database use the code below
await ActivityConnection.UpdateAllAsync(activityItems);


来源:https://stackoverflow.com/questions/56121773/how-to-enable-switch-on-multi-select-listview-with-binding-in-xamarin-forms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!