Hello all can someone give me a tip what technique to use to display props of different kind of objects with "selection change" event of ListBox. For example i have a Veichle class that is inherited from Car Buses etc. and if i want to display props in a DataGrid from that objects i face a issue i must have "if clause" for every object and i must cast it for the appropriate type it is. Thanks for any help in advance.

private void veichleLst_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
{
    cars = new List<Car>();
    buses = new List<Bus>();
    this.selectDateLbl.Visibility = Visibility.Hidden;

    if (veichleLst.SelectedItem is Car)                   < -- #1 if check the type of the object                  
            {
        cars.Add((Car)veichleLst.SelectedItem);
        this.veichleGrd.ItemsSource = cars;


        this.choosedCarLbl.Content = this.veichleLst.SelectedItem;
        subOrder._Order.Veichle = (Car)this.veichleLst.SelectedItem;


        if (isDateSelected == true)
        {
            subOrder._Order.changeVeichleHandler += veichle_change;
        }

    }
    else if (veichleLst.SelectedItem is Bus)            < -- #2 if check the type of the object
    {
        buses.Add((Bus)veichleLst.SelectedItem);
        this.veichleGrd.ItemsSource = buses;

        subOrder._Order.Veichle = (Bus)this.veichleLst.SelectedItem;
        if (isDateSelected == true)
        {
            subOrder._Order.changeVeichleHandler += veichle_change;
        }

        this.choosedCarLbl.Content = this.veichleLst.SelectedItem;

    }
}

1 Answers

3
mm8 On Best Solutions

Since you seem to do the very same thing for both (all?) veichle types, you could cast the SelectedItem to a Veichle:

private void veichleLst_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
{
    this.selectDateLbl.Visibility = Visibility.Hidden;
    if (this.veichleLst.SelectedItem is Veichle veichle)
    {
        subOrder._Order.Veichle = veichle;
        if (isDateSelected == true)
        {
            subOrder._Order.changeVeichleHandler += veichle_change;
        }

        this.choosedCarLbl.Content = veichle;
        this.veichleGrd.ItemsSource = new List<Veichle>(1) { veichle };
    }
}

If you want to access some specific property of a specific type, you will have to cast to this specific type though.