繁体   English   中英

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

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

我正在这样填充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;

如何为每个ComboBoxItem设置一些不同的值。

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

item.Tag = fx.FunctionValue;

两种选择

  1. 您可以从ComboBoxItem创建派生类型,并在派生类型中定义属性。

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

绑定组合框以显示源和绑定源

SelectedValue和DisplayMemberPath如何拯救我的生命

这个小滴答声可能会帮助某人

<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();

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

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

属性列表是myclass的列表

暂无
暂无

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

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