赞
踩
- <ComboBox x:Name="cmb_radius" Height="30" Width="65" FontSize="15"
- DisplayMemberPath="Value" SelectedValuePath="Key" HorizontalAlignment="Center"
- VerticalAlignment="Center" Margin="3" SelectionChanged="cmb_radius_SelectionChanged"/>
- public class ComboBoxEntity
- {
- public string Key { get; set; }
- public string Value { get; set; }
- }
-
- cmb_radius.Items.Clear();
- List<ComboBoxEntity> lcb = new List<ComboBoxEntity>();
- for (int i = 0; i < M_Radius.Columns.Count; i++)
- {
- ComboBoxEntity cbe = new ComboBoxEntity();
- cbe.Key = M_Radius.Columns[i].ColumnName;
- cbe.Value = M_Radius.Rows[0][i].ToString();
-
- // 添加ComboBoxEntity对象到列表中
- lcb.Add(cbe);
- }
-
- // 设置cmb_radius的ItemsSource为lcb
- cmb_radius.ItemsSource = lcb;

- private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
- {
- ComboBox comboBox = (ComboBox)sender;
- // 获取选中的项
- object selectedValue = comboBox.SelectedItem;
-
- // 需要的业务逻辑处理
- if (selectedValue != null)
- {
- string cbKey = (selectedValue as ComboBoxEntity).Key;
- string cbValue = (selectedValue as ComboBoxEntity).Value;
- }
- //...
- }
如果SelectedValue赋值时,赋值的数据不在ComboBox的数据源,此时不会直接引发错误或异常。相反,ComboBox的SelectedValue属性将保持未设置状态(如果之前没有设置过),或者如果已经设置了DataSource但ValueMember未正确配置,则可能会显示默认值,如“System.Data.DataRowView”。这取决于ComboBox的绑定情况和你如何处理数据。
具体表现可能包括:
SelectedValue保持默认值:如果没有匹配的项,SelectedValue可能保持为null,或者如果之前有赋值操作,则可能是之前的值。
SelectedIndexChanged事件可能不会触发:因为没有实际改变选定的索引或匹配到的项。
界面显示不受影响:ComboBox的文本部分(SelectedText)可能不变,或者显示为之前选择的项,而不会因为这次无效的赋值而改变。
为了避免这种情况,可以在赋值前检查DataSource中是否存在匹配的项,可以通过以下方式实现:
- object desiredValue = ...; // 你想设置的值
- var item = comboBox1.DataSource.Cast<object>().FirstOrDefault(item => item.ToString() == desiredValue.ToString());
- if (item != null)
- {
- comboBox1.SelectedValue = desiredValue;
- }
- else
- {
- // 处理不存在的情况,比如记录日志、提示用户等
- MessageBox.Show("指定的值在ComboBox中不存在。");
- }
这段代码首先尝试从DataSource中找到匹配desiredValue
的项,如果找到了就设置SelectedValue,否则可以进行相应的错误处理。注意,这里的比较(item.ToString() == desiredValue.ToString()
)假设值可以用字符串表示,并且这种方式比较简单,可能需要根据实际的数据类型和比较逻辑调整。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。