Skip to main content
 首页 » 编程设计

c#之Button Click to get an Object on SelectionChanged 事件

2024年02月13日16kuangbin

我有一个 SelectionChanged 事件并且工作得很好,但我想弄清楚如何在单击按钮时“捕获”这个选定的项目,他们需要将它作为参数传递给另一个页面,并且编辑此项目。这是我仍然实现的当前代码和按钮 SelectionChanged,因为这是我需要的。

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

我需要编辑这个按钮上的 selectedItem:

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

如果你也能告诉我如何将对象作为参数传递就完美了。

请您参考如下方法:

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

现在在

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

这是很好的做法,只为临时目的创建一个类变量是 hack