简体   繁体   中英

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.

如果您要设置的值仅在后端使用,而不显示给用户,则Tag属性可能是最好的选择。

item.Tag = fx.FunctionValue;

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

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"); } } } 
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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM