简体   繁体   English

如何从C#代码设置WPF ComboBox Item的值

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

I am populating my WPF ComboBox like this 我正在这样填充WPF ComboBox

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. 如何为每个ComboBoxItem设置一些不同的值。

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

item.Tag = fx.FunctionValue;

Two options 两种选择

  1. You can create derived type from ComboBoxItem, and define properties in derived type. 您可以从ComboBoxItem创建派生类型,并在派生类型中定义属性。

  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. 您可以创建项目的任意集合(使用自定义属性),并将ComboBox.ItemsSource设置为该集合,并将DisplayMemberPath设置为需要在组合框中显示的字段。

Binding combobox to display source and binding source 绑定组合框以显示源和绑定源

How SelectedValue and DisplayMemberPath saved my life SelectedValue和DisplayMemberPath如何拯救我的生命

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 将此添加到要向其添加组合框的编辑器模板中=> mkvc是用于保存我的数据的类

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

propertylist is list of myclass 属性列表是myclass的列表

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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