Question

I have a SelectionChanged event and works perfectly, but I want to figure out how to "catch" this selected item at the click of a button they need to pass it as parameter to another page and edit this Item. Here's the current code and button SelectionChanged I still implemented because this is what I need.

private void listCarros_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
    {
        ListBox listBox = sender as ListBox;

        if (listBox != null && listBox.SelectedItem != null)
        {
            //pega o Carro que foi selecionado
            Carro sCar = (Carro)listBox.SelectedItem;

            btnEditCar.IsEnabled = true;
            btnDeleteCar.IsEnabled = true;
        }
        else
        {
            btnEditCar.IsEnabled = false;
            btnDeleteCar.IsEnabled = false;
        }
    }

I need to edit the selectedItem on this button:

private void btnEditCar_Click(object sender, EventArgs e)
{
    //Here I need access to the selectedItem on SelectionChanged event.  
}

If you could also tell me how to pass the object as parameter would be perfect.

Was it helpful?

Solution 2

To give a better idea on my comments. Creating a class level variable is like this:

Notice that sCar is declared outside the method, but within the class.

Carro sCar = new Carro();
private void listCarros_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
{
    ListBox listBox = sender as ListBox;
    if (listBox != null && listBox.SelectedItem != null)
    {
        sCar = (Carro)listBox.SelectedItem;

...

private void btnEditCar_Click(object sender, EventArgs e)
{
    sCar.ProperyYouWantToChange = "Stuff I want to change"
}

OTHER TIPS

You can do this with binding also

1.Bind ListBoxItem(Carro Object) to the tag of "btnEditCar" in xaml.

Xaml should be like this

<Button Name="btnEditCar" OnClick="btnEditCar_Click" Tag="{Binding}"/>

and now in

private void btnEditCar_Click(object sender, EventArgs e)
{
    Carro sCar=(Carro)((sender as FrameworkElement).Tag)
}

This is the good practice,creating a class variable only for temporary purpose is hack

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top