perplexedDev
perplexedDev

Reputation: 835

Set a default value to combobox in WPF

I have a combobox to which I assign values as below:

<ComboBox Height="33" VerticalAlignment="Top"
          ItemsSource="{Binding ProductsList}"
          SelectedValue="{Binding ProductName,Mode=TwoWay}" 
          DisplayMemberPath="ProductName"
          SelectedValuePath="ProductID"/>

I add a value "ALL" to the collection ProductsList. I have a combobox column in a datagrid which uses the same ProductList, which shouldnt show "ALL". Is there a way to add ALL to the combobox in XAML rather than adding it to the collection?

Upvotes: 2

Views: 1404

Answers (2)

sa_ddam213
sa_ddam213

Reputation: 43634

You can use a CompositeCollection, This allows you to combine collections and static items into a single ItemSource

Example:

<ComboBox>
    <ComboBox.Resources>
        <CollectionViewSource x:Key="Products" Source="{Binding ProductsList}"/>
    </ComboBox.Resources>
    <ComboBox.ItemsSource>
        <CompositeCollection>
            <ComboBoxItem>All</ComboBoxItem>
            <CollectionContainer Collection="{Binding Source={StaticResource Products}}" />
        </CompositeCollection>
    </ComboBox.ItemsSource>
</ComboBox>

Note: You will have to create a CollectionViewSource for your ProductsList to use it in the CollectionContainer but that's pretty trivial. You mentioned that you are using the ProductsList elsewhere so you could define the CollectionViewSource in the Window.Resources or views Resources instead of in the ComboBox resources then you can reuse it.

Upvotes: 2

Athari
Athari

Reputation: 34293

You can add "ALL" to ProductsList, but hide it using CollectionView.Filter where you don't need it.

See CollectionView Class.

Upvotes: 0

Related Questions