wpf-combobox

SelectionChanged

private void cmb_history_type_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
string str = ((sender as ComboBox).SelectedItem as ComboBoxItem).Content as string;

...
}
string str = (cmb_filter_subject.SelectedItem as ComboBoxItem).Content as string;

获取当前文字

string str = (cmb_filter_state.SelectedValue as ComboBoxItem).Content.ToString();

样例-动态获取

<ComboBox Name="cmb_account" Height="25" ItemsSource="{Binding CollUserInfo}" 
SelectedValue="{Binding ID, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"
SelectedValuePath="Model_data" DisplayMemberPath="Name" />

DataContext = new VMUserInfo();

public class Model_data
{
[PrimaryKey, AutoIncrement]
public int ID { get; set; }
// 登录账户名
public string Name { get; set; }
// 用户姓名
public string UserName { get; set; }
[Unique]
public string WorkId { get; set; }
public string Password { get; set; }
// 机床号
public int MachineId { get; set; }
public string Memo { get; set; }
}

public class NotifyUIBase : INotifyPropertyChanged
{
// Very minimal implementation of INotifyPropertyChanged matching msdn
// Note that this is dependent on .net 4.5+ because of CallerMemberName
public event PropertyChangedEventHandler PropertyChanged;
public void RaisePropertyChanged([CallerMemberName] String propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}

public class VMUserInfo : NotifyUIBase
{
public ObservableCollection<Model_data> CollUserInfo { get; set; }
public ObservableCollection<string> CollMachineInfo { get; set; }

public VMUserInfo()
{
CollUserInfo = App.db.List_userData();
CollMachineInfo = new ObservableCollection<string>();
for (var i = 0; i < 10; i++)
{
CollMachineInfo.Add($"{i+1:d03}");
}
RaisePropertyChanged("CollUserInfo");
RaisePropertyChanged("CollMachineInfo");
}
}
// 简单字符串
<ComboBox Name="cmb_zeroMasterType" MinWidth="50" Height="25"
SelectedItem="{Binding SimpleStringProperty,Mode=OneWayToSource}"
VerticalContentAlignment="Center"
SelectedIndex="0"
Margin="5,0,5,0"/>

静态字符串

<ComboBox x:Name="cmb_operate_type" Margin="4,0" Height="25" VerticalContentAlignment="Center">
<ComboBoxItem IsSelected="True">买入</ComboBoxItem>
<ComboBoxItem >卖出</ComboBoxItem>
</ComboBox>
// 自定义类

public class Model_sensor
{
[PrimaryKey, AutoIncrement]
public int ID { get; set; }
// 名称
public string Name { get; set; }
// 描述
public string Comment { get; set; }
...
}

<ComboBox Name="cmb_sensor" IsEditable="False" VerticalAlignment="Center" MinWidth="150" Height="25" Margin="2"
ItemsSource="{Binding Path=Model_sensor}"
SelectedValue="{Binding Name, UpdateSourceTrigger=PropertyChanged, Mode=OneWay}"
DisplayMemberPath="Name"
SelectedValuePath="Name"
SelectionChanged="cmb_sensor_SelectionChanged"/>

var mainwin = (MRLGauger.MainWindow)Application.Current.MainWindow;
cmb_sensor.ItemsSource = mainwin.ucmsv.collectionSensor;

事件

<DataGridTemplateColumn Header="动态/静态">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ComboBox ItemsSource="{Binding DataContext.collectionMeasureType, RelativeSource={RelativeSource AncestorType=local:UCMeasureStep}}"
SelectedValue="{Binding measureType, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"
SelectionChanged="ComboBox_SelectionChanged" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (FLAG_LOADED == (Flag & FLAG_LOADED) )
{
// old value
var result = (sender as ComboBox).Text;
// new value
string text = (sender as ComboBox).SelectedItem as string;
}

}

设定默认值

正确绑定映射关系后,有数据会自动设置默认值

// 通过对象初始化选择项
cmb_k6Info.SelectedItem = App.db.m_K6Info[0];

// 通过 项目索引
cmb_postgraduateRecommendation.SelectedIndex = 1;

<DataGridTemplateColumn Header="所属标准件">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ComboBox Name="cmb_masterDup" ItemsSource="{Binding DataContext.collectionMaster, RelativeSource={RelativeSource AncestorType=local:UCMasterPiece}}"
SelectedValue="{Binding MasterID, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"
SelectedValuePath="MasterID" DisplayMemberPath="Name"
SelectionChanged="cmb_masterDup_SelectionChanged" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

public ObservableCollection<Model_master> collectionMaster { get; set; }

public class Model_master_duplicate
{
[PrimaryKey, AutoIncrement]
public int ID { get; set; }
...
// 副本所属的 master 的ID
public int MasterID { get; set; }
...
}

public class Model_master
{
[PrimaryKey, AutoIncrement]
public int ID { get; set; }
public string Name { get; set; }
...
}

删除

private void btn_delete_k6key_Click(object sender, RoutedEventArgs e)
{
ModelK6Info item = (ModelK6Info)cmb_k6Info.SelectedItem;
var len = App.db.m_K6Info.Count;
for (int i = 0; i < len; ++i)
{
if (App.db.m_K6Info[i].K6Key == item.K6Key)
{
App.db.Delete_model<ModelK6Info>(item,item.ID);
App.db.m_K6Info.RemoveAt(i);
}
}
if (0 < App.db.m_K6Info.Count)
{
cmb_k6Info.SelectedItem = App.db.m_K6Info[0];
}

}

属性区别

Their names can be a bit confusing :). Here’s a summary:

The SelectedItem property returns the entire object that your list is bound to. So say you’ve bound a list to a collection of Category objects (with each Category object having Name and ID properties). eg. ObservableCollection. The SelectedItem property will return you the currently selected Category object. For binding purposes however, this is not always what you want, as this only enables you to bind an entire Category object to the property that the list is bound to, not the value of a single property on that Category object (such as its ID property).

Therefore we have the SelectedValuePath property and the SelectedValue property as an alternative means of binding (you use them in conjunction with one another). Let’s say you have a Product object, that your view is bound to (with properties for things like ProductName, Weight, etc). Let’s also say you have a CategoryID property on that Product object, and you want the user to be able to select a category for the product from a list of categories. You need the ID property of the Category object to be assigned to the CategoryID property on the Product object. This is where the SelectedValuePath and the SelectedValue properties come in. You specify that the ID property on the Category object should be assigned to the property on the Product object that the list is bound to using SelectedValuePath=’ID’, and then bind the SelectedValue property to the property on the DataContext (ie. the Product).

The example below demonstrates this. We have a ComboBox bound to a list of Categories (via ItemsSource). We’re binding the CategoryID property on the Product as the selected value (using the SelectedValue property). We’re relating this to the Category’s ID property via the SelectedValuePath property. And we’re saying only display the Name property in the ComboBox, with the DisplayMemberPath property).

<ComboBox Name="cmb_command" Width="120" Height="25" IsEditable="True" 
ItemsSource="{Binding Categories}"
SelectedValue="{Binding CategoryID, Mode=TwoWay}"
SelectedValuePath="ID"
DisplayMemberPath="Name" />

public class Category
{
public int ID { get; set; }
public string Name { get; set; }
}

public class Product
{
public int CategoryID { get; set; }
}

no dropdown

private void cmb_driver_DropDownOpened(object sender, EventArgs e)
{
// 未登录不允许修改
var mainwin = (MRLGauger.MainWindow)Application.Current.MainWindow;
if (MainWindow.FLAG_USER_ADMIN != (mainwin.flag&MainWindow.FLAG_USER_ADMIN))
{
ComboBox cb = sender as ComboBox;
cb.IsDropDownOpen = false;
}

}

注意事项

绑定 combobox 的时候要注意使用 int 类型,不支持 Int64