Lamloumi Afif
Lamloumi Afif

Reputation: 9081

Changing combobox item background color within wpf application

I have a wpf application in which I need to customize a combobox to make it editable.

public class AutoCompleteFacturation: ComboBox 
{
    List<vue_fsign_fiche_signaletique> liste = new List<vue_fsign_fiche_signaletique>();
    // [...]
    ItemsSource = NewDataSource;
    liste = NewDataSource.ToList<vue_fsign_fiche_signaletique>();
    ComboBoxItem item = (ComboBoxItem)base.Items[0];
    item.Background = System.Windows.Media.Brushes.AliceBlue;
}

I need to change the background of the first item ComboBoxItem item = (ComboBoxItem)base.Items[0]; ==> I get an exception indicates that the cast of vue_fsign_fiche_signaletique to ComboBoxItem is not possible.

So How can I fix this to coloriate the first item of the combobox ?

Thanks

Upvotes: 1

Views: 706

Answers (2)

A.Caillet
A.Caillet

Reputation: 101

You binded your ComboBox on your list.

So Items return a list of vue_fsign_fiche_signaletique

2 Possibilities :

foreach (vue_fsign_fiche_signaletique fiche in liste) { ComboBoxItem i = new ComboBoxItem(); i.Content = fiche.Text; i.Background = System.Windows.Media.Brushes.AliceBlue; base.Items.Add(i); }

Or wrap your vue_fsign_fiche_signaletique in a View Model and use a IValueConverter

Upvotes: 1

Arie
Arie

Reputation: 5373

The item you're getting is the one that is bound using DataSource (here of type vue_fsign_fiche_signaletique).

What you need is ComboBoxItem, which is a container. To get it, use ItemContainerGenerator.ContainerFromIndex(index) or ItemContainerGenerator.ContainerFromItem(item):

https://msdn.microsoft.com/library/ms750552(v=vs.90).aspx

Upvotes: 2

Related Questions