Abhi
Abhi

Reputation: 5561

How to set value of WPF ComboBox Item from C# Code

I am populating my WPF ComboBox like this

foreach (Function fx in XEGFunctions.GetAll())
{
    ComboBoxItem item = new ComboBoxItem();
    item.Content = fx.Name;
    item.ToolTip = fx.Signature;               
    //item.( some property ) = fx.FunctionValue;
    cmbBoxTransformation.Items.Add(item);
}
cmbBoxTransformation.SelectedIndex = 0;

How can I set some different value to each ComboBoxItem.

Upvotes: 1

Views: 18758

Answers (4)

Mahdi Khalili
Mahdi Khalili

Reputation: 1188

var listItems = val.Split('$');
DataTemplate dt = new DataTemplate();
var combo = new FrameworkElementFactory(typeof(ComboBox));
combo.SetValue(ComboBox.ItemsSourceProperty, listItems);
combo.SetValue(ComboBox.SelectedValueProperty, "Whatever");
combo.SetBinding(ComboBox.SelectedValueProperty, new Binding("Value") { Source = mkvc });
dt.VisualTree = combo;
dt.Seal();

add this to editor template of whatever you want to add combobox to it => mkvc is a class for holding my data

PropertyDefinition pd = new PropertyDefinition();
pd.EditorTemplate = dt;
//rpg =>radPropertyGrid
rpg.PropertyDefinitions.Add(pd);
rpg.Item = propertyList;

propertylist is list of myclass

Upvotes: 0

zamoldar
zamoldar

Reputation: 598

this little tick may helps someone

<ComboBox SelectedIndex="1" SelectedValuePath="Tag"  SelectedValue="{Binding SampleDept,Mode=OneWayToSource}" >
                                <ComboBoxItem Content="8-bit" Tag="8"  ></ComboBoxItem>
                                <ComboBoxItem Content="16-bit" Tag="16" ></ComboBoxItem>
                                <ComboBoxItem Content="24-bit" Tag="24"></ComboBoxItem>
                                <ComboBoxItem Content="32-bit" Tag="32"></ComboBoxItem>
                            </ComboBox>
public class SampleModel{

   public int SampleDept{

            get { return _sampleDept; }
            set {
                
                _sampleDept = value;
            OnPropertyChanged("SampleDept");
            }
        }
}

Upvotes: 1

Tilak
Tilak

Reputation: 30688

Two options

  1. You can create derived type from ComboBoxItem, and define properties in derived type.

  2. You can create arbitrary collection of item (with your custom properties), and set ComboBox.ItemsSource to that collection, and DisplayMemberPath to the field that needs to be displayed in the Combobox.

Binding combobox to display source and binding source

How SelectedValue and DisplayMemberPath saved my life

Upvotes: 2

Developer
Developer

Reputation: 2006

If the value you're looking to set is only used in the back end, and not displayed to the user, the Tag property is probably your best bet.

item.Tag = fx.FunctionValue;

Upvotes: 5

Related Questions