darkArk
darkArk

Reputation: 144

Binding certain elements from a list to a combobox

I have the following question: In my view model I have a list with an object that has a property Name and Value, both strings. I want to bind the list to a combo box in my view, but I want to display only the elements that have a certain name. For the list:

Name    Value
foo    aaa
bar    bbbb
foo    ccc

I want to display in the combobox only the elements that have the name foo, aaa and ccc. The catch here is that I want to do the filter in the view and not in the codebehind or the viewmodel.

ViewCode:

<ComboBox IsEditable="True" VerticalAlignment="Top" 
      HorizontalAlignment="Left" Width="150" Margin="60,60,0,0" 
      ItemsSource="{Binding Elements}"  
      SelectedValue="{Binding Value}" SelectedValuePath="Value" 
      DisplayMemberPath="Value" />

ViewModel Code:

private List<CustomChartElement> elements;
public List<CustomChartElement> Elements
    {
        get { return this.elements; }
    }

Upvotes: 0

Views: 559

Answers (1)

Marwie
Marwie

Reputation: 3307

You could just add a property that does the filtering and bind to that one instead of the list you exposed.

If you have several comboboxes and each one requires a sublist of the base list filtered according to different filter logics you will have to think about implementing each list in your model as it's own property in the view. You may consider to also encapsule your model inside a container class which exposes the different lists to not clutter up your base model.

I found an idea to do so called Command Binding. Here is an example with passing a parameter. It may be what you were looking for.

Since it requires ICommandSource, you might want to have a look at the article here on how to implement ICommandSource for Combobox it.

Upvotes: 1

Related Questions