简体   繁体   English

ButtonClick在SelectionChanged事件上获取一个Object

[英]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. 我有一个SelectionChanged事件并且工作得很好,但是我想弄清楚如何通过点击一个按钮来“捕获”这个所选项目,他们需要将它作为参数传递给另一个页面并编辑这个项目。 Here's the current code and button SelectionChanged I still implemented because this is what I need. 这是我仍然实现的当前代码和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;
        }
    }

I need to edit the selectedItem on this button: 我需要在这个按钮上编辑selectedItem:

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. 1.将ListBoxItem(Carro对象)绑定到xaml中的“btnEditCar”标记。

Xaml should be like this Xaml应该是这样的

<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 这是一个很好的做法,只为临时目的创建一个类变量是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. 请注意, sCar是在方法之外声明的,但在类中。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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