Quantcast
Channel: Xamarin.Forms — Xamarin Community Forums
Viewing all articles
Browse latest Browse all 77050

SQLite How to change color of label when image is pressed?

$
0
0

I have been working on this for the last 2 days and cannot figure it out. So I am trying to basically when the user presses on a image in the listview that the label colour changes. So far I have gotten this to work somewhat, but the problem is saving the value to SQLite. If I change the tab or restart the app it goes back to the default colour, I believe this is because the value is not been saved to the database. I can't save it because SQLite doesn't accept type of 'Color'. This is my code:

This is the Model (I am using MVVM architecture)
` public class UserModel
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }

    //retrieve item name
    public string ItemName { get; set; }

    //retrieve current day
    public string DateTimeSet { get; set; }

    public bool Selected { get; set; }

    public string date { get; set; }

    [Ignore]
    public Color SelectedColor { get; set; }

    //public Color SelectedListViewItemColor { get; set; }

    //select color based on condition of if statement


    [Ignore]
    public Color DefaultColor
    {
        set
        {
            //set default color of text

            SelectedColor = value;

        }

        get
        {
            return SelectedColor;                
        }
    }


}

}
`
The view

`public partial class TasksPageView : ContentPage
{
private INavigation nav;
private TaskPageViewModel tpvm;

    public TasksPageView ()
    {
        nav = Navigation;
        tpvm = new TaskPageViewModel(nav);
        BindingContext = tpvm;
        InitializeComponent ();


    }

    protected override void OnAppearing()
    {
        tpvm.BindItems();
    }

}`

The view

` <ContentPage.Resources>



Blue

</ContentPage.Resources>

<ContentPage.Content>
    <RelativeLayout>
        <ListView ItemsSource="{Binding ListItems}" x:Name="llv" SelectedItem="{Binding SelectedListViewItem, Mode=TwoWay}" HasUnevenRows="True">
            <ListView.Header>
                <StackLayout Padding="10,5,0,5" VerticalOptions="Center" HorizontalOptions="Center">
                    <Label Text="{Binding Datetime}"/>
                </StackLayout>
            </ListView.Header>
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <StackLayout>
                            <StackLayout Orientation="Horizontal">
                                <Label Text="{Binding ItemName}" TextColor="{Binding DefaultColor}" VerticalOptions="Center" HorizontalOptions="StartAndExpand" Margin="5,5,5,5" />
                                <Label Text="{Binding DateTimeSet}" Margin="5,5,5,5" VerticalOptions="Center" HorizontalOptions="End"/>
                                <Image Source="icon.png" VerticalOptions="CenterAndExpand" HeightRequest="20" WidthRequest="20" ClassId="{Binding Id}" >
                                    <Image.GestureRecognizers>
                                        <TapGestureRecognizer
                                            Command="{Binding Path=BindingContext.PlayOrPauseButtonPressed, Source={x:Reference taskspageview}}" 
                                            NumberOfTapsRequired="1" CommandParameter="{Binding .}" >

                                        </TapGestureRecognizer>

                                    </Image.GestureRecognizers>
                                </Image>

                            </StackLayout>

                        </StackLayout>
                        <ViewCell.ContextActions>
                            <MenuItem Text="Delete" IsDestructive="True" Command="{Binding Source={x:Reference llv}, Path=BindingContext.DeleteSingleTask}"
                                CommandParameter="{Binding .}"/>
                        </ViewCell.ContextActions>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>

        <controls:FloatingActionButton HorizontalOptions="CenterAndExpand" 
                                   WidthRequest="100" HeightRequest="100" 
                                   VerticalOptions="CenterAndExpand" 
                                   Command="{Binding AddButton}"
                                   Image="icon.png" ButtonColor="#03A9F4" RelativeLayout.XConstraint="{ConstraintExpression Type=RelativeToParent, 
            Property=Width, Factor=1, Constant= -98}"
            RelativeLayout.YConstraint="{ConstraintExpression Type=RelativeToParent, Property=Height, Factor=1, Constant=-98}" />
    </RelativeLayout>
</ContentPage.Content>`

The ViewModel
`
[AddINotifyPropertyChangedInterface]
public class TaskPageViewModel
{
//for navigation purposes
public INavigation _navigation;
public INavigation nav;

    //dbconnector
    private static DatabaseHelper dbhelper;

    //command to add item to listview
    private ICommand Addbtn;

    //command to save teh item to database and observablecollection
    private ICommand save;

    //command to delete task that the user has pressed on.
    private ICommand _DeleteSingleTask;

    private ICommand StartPlayOrPauseButton;

    private ObservableCollection<UserModel> items;
    private List<UserModel> _itemsList;

    //retrieve the item name in the UserModel class
    private UserModel _itemName { get; set; }

    //this is what will hold the listview items
    private UserModel _SelectedListViewItem { get; set; }

    //current task
    private string task;


    private string TimeStarted { get; set; }      

    //null because might not need to pass with parameter
    public TaskPageViewModel(INavigation navigation = null)
    {
        //set the nevigation
        nav = navigation;

        //create new db
        CreateNewDb();

    }

    //create new db
    public static DatabaseHelper CreateNewDb()
    {
        //if null create new database
        if (dbhelper == null)
        {
            dbhelper = new DatabaseHelper();
        }

        return dbhelper;
    }

    //add button to add new task
    public ICommand AddButton
    {
        get => Addbtn ?? (Addbtn = new Command(() =>
        {
            nav.PushAsync(new NewItemAddView(this));
        }));
    }

    //delete listview item task both from db and from observablecollection
    public ICommand DeleteSingleTask
    {
        get => _DeleteSingleTask ?? (_DeleteSingleTask = new Command((UserModel) =>
        {
            //get selected listview item and convert it to userModel
            _SelectedListViewItem = (UserModel)UserModel;

            //remove from list
            ListItems.Remove((UserModel)UserModel);

            //   MessagingCenter.Send(this, "xyz", ListItems.Count);

            dbhelper.DeleteIndividualItem(_SelectedListViewItem.Id);

        }));
    }

    //add task
    public ICommand AddTask
    {
        get => save ?? (save = new Command(() =>
        {
            //current task
            var currentTask = Task;

            //current time on phone
            var currentTime = DateTime.Now.ToString("HH:mm");

            List<string> StorageForTime = new List<string>();

            //create new user model
            UserModel task = new UserModel
            {
                //set the item name to current task and datetimeset to current time
                ItemName = currentTask,
                DateTimeSet = currentTime
                //  DateTimeSet = currentTime
            };
            ListItems.Add(task);

            //insert in db the task
            dbhelper.InsertItem(task);
        }));
    }

    public ICommand PlayOrPauseButtonPressed
    {
        get => StartPlayOrPauseButton ?? (StartPlayOrPauseButton = new Command((UserModel) =>
        {
            //var SelectedItemId = ListItems.Where(i => i.Id == (int)UserModel);
            UserModel selectedUser = (UserModel)UserModel;

            selectedUser.DefaultColor = Color.Pink;

            dbhelper.UpdateItem(selectedUser);



            //set value to selecteditem in listview ID
            //if (true)
            //{

            //}
          //  StartTimer(IdOfSelectedItem);


            //IEnumerable<UserModel> currentlySelectedItem;
            //currentlySelectedItem = SelectedListViewItem1;

            //Device.StartTimer(TimeSpan.FromSeconds(1), () =>
            //{
            //    Device.BeginInvokeOnMainThread(() =>
            //        currentlySelectedItem.First().DateTimeSet = DateTime.Now.ToString("HH.mm:ss")

            //        );

            //    return true;
            //});

        }));
    }

    //return the task
    public string Task
    {
        get { return task; }
        set
        {
            task = value;
        }
    }

    //return only item name
    public string ItemName
    {
        get => _itemName.ItemName;
        set
        {
            _itemName.ItemName = value;

        }
    }

    public string TimeStart
    {
        get => TimeStarted;
        set
        {
            TimeStarted = value;
        }
    }


    public UserModel SelectedListViewItem
    {
        get { return _SelectedListViewItem; }
        set
        {
            if (_SelectedListViewItem != null)
                _SelectedListViewItem.Selected = false;

            _SelectedListViewItem = value;
            //set to false first incase its true already.
            //   _SelectedListViewItem.Selected = false;

            //if bool is item selected is false
            if (_SelectedListViewItem.Selected == false)
            {
                // then set the state to true since the item has been pressed.
                //     _SelectedListViewItem.Selected = true;

                //MessagingCenter.Send<TaskPageViewModel, string>(this, "Detail", _SelectedListViewItem.ItemName);
            }

        }
    }

    //once the user presses on a listview item then start the timer
    public void StartTimer(UserModel selectedListViewItem)
    {
        //_SelectedListViewItem = (UserModel)selectedListViewItem;

    }

    //observablecollection that contains UserModel items
    public ObservableCollection<UserModel> ListItems
    {
        get => items;
        set
        {
            items = value;
        }
    }

    //bind items to listview
    public void BindItems()
    {
        _itemsList = dbhelper.GetAllItemsData().ToList();

        ListItems = new ObservableCollection<UserModel>(_itemsList);
    }
}

}`


Viewing all articles
Browse latest Browse all 77050

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>