HOW TO GET INDEX OF A ROW FROM LISTVIEW FROM BUTTONS INSIDE LISTVIEW

CYFERIOUSCYFERIOUS Member ✭✭

ok i need to get index of listview item from buttons inside listview item, without give a tapped in listview item...sounds tricky

-------Listview item1-------

button1 button2 button3

-------Listview item2-------

button1 button2 button3

if i press button 1 in Listview item1 i wil get the index of Listview item1 wich is 0, and if i press button 1 in Listview item2 i wil get the index of Listview item2 wich is 1, and so on... im not clicking the listview item...

i have this

.xaml

 <StackLayout Grid.Column="0" Grid.Row="6">

                                    <Button Clicked="OnLikeClick" CommandParameter="{Binding .}" Text="popo"   /> 

.cs

public void OnLikeClick(object sender, EventArgs args)
{

        Button button = (Button)sender;
        StackLayout listViewItem = (StackLayout)button.Parent;



        System.Diagnostics.Debug.WriteLine("index:>" + listViewItem.index?????);




    }

thanks

im really new in xamarin

Tagged:

Answers

  • ClintStLaurentClintStLaurent USUniversity ✭✭✭✭✭

    ok i need to get index of listview item from buttons inside listview item,

    Stop. Why?

    99% of the time this is wrong. You already have the entire object that is in the collection source of the ListView. What do you need the index for? This is usually someone using some OLD OLD technique from 2001 Windows Forms or similar.

  • ClintStLaurentClintStLaurent USUniversity ✭✭✭✭✭

    <Button Clicked="OnLikeClick"

    What the...?
    Are you using UI events like Click to drive logic and events and responses other than UI?

  • CYFERIOUSCYFERIOUS Member ✭✭
    edited May 6

    i just need to get de index for retrieve data from a service in its own order of loading. i dont get " OLD OLD technique from 2001 Windows Forms " . what do you mean? i have seen some post in stack and here, and they do what im posting, but i cant get the index yet. thanks for read.

    .cs
    public void OnLikeClick(object sender, EventArgs args)
    {
    DisplayAlert("Alert", ObjProductoList.datos[¿¿indexOFrow??].IdPromoSuscriptor, "ok");
    }

  • CYFERIOUSCYFERIOUS Member ✭✭
    edited May 6

    actually android studio uses recycler view, in each row inside recycler view there is a button that get the id of the object, but in xamarin.forms (android - IOS ) we use listview for this approach. basically we have a card view that is populated before show itself, and get the properties of the objects without index, so we use oncreateViewHolder & onBindViewHolder, but really we dont know to do it in xamarin.forms. thanks i hope to be clear.

  • ClintStLaurentClintStLaurent USUniversity ✭✭✭✭✭

    @CYFERIOUS said:
    what do you mean? i have seen some post in stack and here, and they do what im posting,

    Just because you see other noobies such as yourself doing old/wrong things that we haven't done in 15 years doesn't mean its good practice. It just means they either
    1. Are following old tutorials because nothing dies on the internet
    2. They are following their college textbook because there is no motivation for colleges to stay current
    3. They are foreign outsources

    i just need to get de index for retrieve data from a service in its own order of loading

    This is what I find odd. You already know the order because you had to get data to begin with in order to put it into the ListView. Order of display should be basically meaningless. Maybe they sort by age... maybe its sorted alphabetically... Maybe its by kingdom order of species of the user's pets... The point is, any time you are using the UI to control logic you're going down a {probably} bad path. In modern software your code could run with NO UI.

    Not to mention... You do realize that your ViewModel could be binded to more than one View, right? So if the data is alphabetic in one view, and reverse alphabetic in another view... what do you do? And why does it matter what order the ListView was sorted in when you fetch the data? Its just data. Fetch, sort, filter, after you get it.

    And as I said... You already have the entire actual object that is in the ListView. That means you should already have the database ID of the object the user clicked on. So you fetch more data using the ID, not the position in a list. That's just nuts.

    @CYFERIOUS said:
    actually android studio uses recycler view, in each row inside recycler view there is a button that get the id of the object, but in xamarin.forms (android - IOS ) we use listview for this approach. basically we have a card view that is populated before show itself, and get the properties of the objects without index, so we use oncreateViewHolder & onBindViewHolder, but really we dont know to do it in xamarin.forms. thanks i hope to be clear.

    Well that's a good explaination of what I was saying about bad design. You're not bothering to learn how things are done in 2019 in Xamarin forms. You want to just take what you did in Android, the way its been done for 10+ years and apply that technique to a different environment.
    Its like saying:

    I have a new car with automatic transmission. In the past I've always had to step on the clutch to change gears. How can I continue to step on the clutch even though I have an automatic? I don't want to change what I've been doing all these years.

  • jezhjezh Member, Xamarin Team Xamurai

    I don't think it is a good idea to do like this.
    We can use the ItemSelected function or ItemTappedfunction of ListView in Xamarin form
    For example:
    xaml

            <ListView  x:Name="lstView" RowHeight="60" ItemSelected="OnSelection" ItemTapped="OnTap">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        .........
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    

    Suppose the ItemsSource of the Listview is :

     public ObservableCollection<VeggieViewModel> veggies { get; set; }//VeggieViewModel is the Object Model
     veggies = new ObservableCollection<VeggieViewModel> ();
            veggies.Add (new VeggieViewModel{ Name="Tomato", Type="Fruit", Image="tomato.png"});
            veggies.Add (new VeggieViewModel{ Name="Romaine Lettuce", Type="Vegetable", Image="lettuce.png"});
            veggies.Add (new VeggieViewModel{ Name="Zucchini", Type="Vegetable", Image="zucchini.png"});
            lstView.ItemsSource = veggies;
    

    The OnSelection function

      void OnSelection(object sender, SelectedItemChangedEventArgs e)
        {
            if (e.SelectedItem == null)
            {
                return;
            }
            int selectedIndex = e.SelectedItemIndex;//the selected index of the listview
            VeggieViewModel selectedModel= (VeggieViewModel)e.SelectedItem;// the selected object 
            DisplayAlert("Item Selected", "Name: "+selectedModel.Name +": Type: " + selectedModel.Type, "Ok");
        }
    

    The OnTap function

     void OnTap(object sender, ItemTappedEventArgs e)
        {
            int tapdIndex = e.ItemIndex;           
            VeggieViewModel tapModel = (VeggieViewModel)e.Item;
    
            DisplayAlert("Item Tapped", "Name: " + tapModel.Name + ": Type: " + tapModel.Type, "Ok");
        }
    

    For more details, you can check: https://docs.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/listview/

  • voidstreamvoidstream FRMember ✭✭✭

    Don't use row index, just bind a command which the parameter is the currentItem.
    CommandParameter="{Binding .}"

    If you really need the row index, get the item (from command) index in ItemSource (your binding list).

    View -> Binded command -> ViewModel (handle data, binded properties etc...)
    View -> Event -> Code behind view (only UI code, don't change view data.)

  • CYFERIOUSCYFERIOUS Member ✭✭

    @jezh thanks but we need to get the tap in the buttons inside the listview item, not the listview item. @voidstream we are working with your idea but we dont find a property in our listView called index, it appears getEnumerator.

    @ClintStLaurent thanks man.

    we still working on it.

  • CYFERIOUSCYFERIOUS Member ✭✭

    @ClintStLaurent youre right, about the logic has not to be part of the UI. we´re working on it. we have the ID of the object from data base, but we dont figure it out, how to identify and communicate every group of buttons inside listview item just for "that listview item". we need to sort it, in the way that every group of buttons just communicate data with the listview
    item wich they are belonging to.

    in this case the listview item has an image of xbox, and a group of buttons, so if i click the like button, send an state (0,1) to DB with the ID of item, not the index of the list view. but we need the index for know to wich listview item the group of buttons are belonging to. i hope to be clear.

    thanks man.

  • voidstreamvoidstream FRMember ✭✭✭

    @CYFERIOUS said:
    @jezh thanks but we need to get the tap in the buttons inside the listview item, not the listview item. @voidstream we are working with your idea but we dont find a property in our listView called index, it appears getEnumerator.

    @ClintStLaurent thanks man.

    we still working on it.

    Your tapped item is an object from your ObjProductoList.datos. So just get the IndexOf(YourItem) from your ObjProductoList.datos, not from the ItemsSource property ;)

  • jezhjezh Member, Xamarin Team Xamurai

    @CYFERIOUS said:
    @ClintStLaurent youre right, about the logic has not to be part of the UI. we´re working on it. we have the ID of the object from data base, but we dont figure it out, how to identify and communicate every group of buttons inside listview item just for "that listview item". we need to sort it, in the way that every group of buttons just communicate data with the listview
    item wich they are belonging to.

    in this case the listview item has an image of xbox, and a group of buttons, so if i click the like button, send an state (0,1) to DB with the ID of item, not the index of the list view. but we need the index for know to wich listview item the group of buttons are belonging to. i hope to be clear.

    thanks man.

    If I understand correctly, just as you said, you need the index for know to wich listview item the group of buttons are belonging to, then according to the index of the listview, you will get the item of the Listview.
    After that, you will get the Binding Object Model of the item, then you will get the ID of the item .
    then you can do what you want.

  • CYFERIOUSCYFERIOUS Member ✭✭
    edited May 17

    @jezh yup is what we´re trying to do. but right now we´re working on observable collection because the list ins not updated every time database is updated. thanks!! :smile:

  • ClintStLaurentClintStLaurent USUniversity ✭✭✭✭✭
    edited May 17

    I'm going to say it one last time then shut up.
    Looking at your screen shot is it very very clear that you are not practicing MVVM, good design, or separation of UI from logic.

    This is the crux of the problem you now face. You did bad things in the early stages of your app, are doing bad things now as seen in this screenshot, and now you need a way to patch/band-aid your way out of it. That's why you are trying to get the index from a UI element when you aren't supposed to do that.

    I urge you to either:
    1 - Take the time now to fix you architecture. 20 hours fixing it now will save you 2,000 hours of headache, problem, patching etc.
    2 - If you don't know what's wrong with what you have here... If you think I'm wrong... If you or your team don't have the knowledge/skills to make this right - Then hire someone. Contract someone who is MVVM competent to fix your architecture. There are plenty of people that do like I do and stub out the skeletons of apps for other teams. Once your team has a good design in place, I assume they can do the grunt coding for the various features and modules. You just need a software architect to fix your design.

    Once your design is resolved, you won't have this problem to try to band-aid. Do you see where I'm going here? Cure the illness so you don't have to focus on the symptoms.

  • jezhjezh Member, Xamarin Team Xamurai

    @CYFERIOUS
    Well, if you have any other question, you can create a new thread, we are willing to help you.
    And if the solution is helpful for you , could you please mark it as a answer?

Sign In or Register to comment.