Put / get name of an ITEM in listView WPF

0

I have created a listView that by default shows 6 elements with a field Nombre and another Def in this way:

        listView.Items.Add(new grafica(){Nombre = "Seno de x", Def = "a * sen(b*x)" });
        listView.Items.Add(new grafica(){Nombre = "Coseo de x", Def = "a * cos(b*x)" });
        listView.Items.Add(new grafica(){Nombre = "Potencia de x", Def = "a*xn" });
        listView.Items.Add(new grafica(){Nombre = "Multiplo de x", Def = "a*x +b" });
        listView.Items.Add(new grafica(){Nombre = "Polinomio de x", Def = "a*x2+ b*x +c"});
        listView.Items.Add(new grafica(){Nombre = "Inversa de x", Def = "a/(b*x)" });

grafica() is just a class with its set and get.

My question is, how can I know in listView that one of those elements is selected? Is there a way to name a item and use the nombre.isChecked property to perform operations with that item ?

Thank you!

    
asked by Mario Hernandez 23.10.2018 в 12:17
source

1 answer

0

If what you want is to determine which element of the list is selected you can use

listView.selectedItem

or

listView.Items[listView.SelectedIndex]

Now, if what you want is to determine the value that is selected, remember that "graph" is a class that you surely declared in the following way:

public class grafica
{
   public string Nombre {get; set; } 
   public string Def {get; set ;} 
}

Therefore, when it is assigned as a ListView value, you must convert it for its use, that is, for example:

(grafica)listView.selectedItem

This will allow you to access the properties of your class and verify its contents in the following way:

if (((grafica)listView.selectedItem).Nombre.StartsWith("Seno")) 
{ 
   // Si empieza con "Seno" entonces es seno... 
}

Now if you only want to determine if an element of the ListView has been selected or none you can do the following:

if (listView.SelectedIndex == -1) 
{
   //No hay ningún elemento seleccionado
}
else
{
   //Hay un elemento seleccionado y ese elemento es el que 
   //se encuentra en el índice =  listView.SelectedIndex
}

This also applies to ListBox

    
answered by 29.10.2018 в 20:34