简体   繁体   中英

ButtonClick to get an Object on SelectionChanged event

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.

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

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"
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM