Frage

I have a class with similar structure as given below:-

public class Sample
{
    public List<string> Names { get; private set; }
    public List<int> IDs { get; private set; }

    // Some logic to populate these collections.
}

Now in another XAML file, I need to bind Names property to a ComboBox and based on the selection I need to get the corresponding ID as selected value. Is there way I can solve this problem using binding?

I have an object of Sample class in my model like below:-

public class Model
{
    public Sample Object
    {
       get { return _sample; }
       set { _sample = value; }
    }
}

I'm not allowed to change the Sample entity class. Please guide me on how to solve this problem.

War es hilfreich?

Lösung 2

Your best bet is to wrap the Name and ID into a separate class, then bind the ItemsSource to the collection of Name/ID pairs. Set the DisplayMemberPath on the ComboBox to "Name".

On the View Model, you can have a property for the selected Name/ID pair, or just the selected ID. If you want to do the latter, just set SelectedValuePath to "ID" and bind SelectedValue to the ID property on your view model (note that if you do it this way, you can use the anonymous class projection from Servy's answer). Otherwise, just bind SelectedItem to your selected Name/ID pair property (this version requires a named class).

Andere Tipps

You need to merge the two different lists into a single list of an object with two values before binding, fortunately doing so is rather straightforward, just use Zip:

var data = sample.Names.Zip(sample.IDs, (name, id)=> new{name, id});

Then bind to data as you normally would.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top