簡體   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