wpf ComboBox绑定数据及变更事件

定义ComboBox,以及SelectionChanged事件

cs 复制代码
 <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"/>

实体类及数据绑定

cs 复制代码
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;

SelectionChanged事件的处理

cs 复制代码
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;
    }
    //...
}
相关推荐
henreash1 小时前
C# dll版本冲突解决方案
开发语言·c#
阿蒙Amon4 小时前
C#封装HttpClient:HTTP请求处理最佳实践
开发语言·http·c#
ghost1437 小时前
C#学习第29天:表达式树(Expression Trees)
开发语言·c#
安木夕17 小时前
C#-Visual Studio宇宙第一IDE使用实践
前端·c#·.net
gregmankiw20 小时前
C#调用Rust动态链接库DLL的案例
开发语言·rust·c#
阿蒙Amon21 小时前
06. C#入门系列【自定义类型】:从青铜到王者的进阶之路
开发语言·c#
钢铁男儿1 天前
C# 表达式和运算符(表达式和字面量)
开发语言·c#
林鸿群1 天前
C#子线程更新主线程UI及委托回调使用示例
开发语言·c#
o0向阳而生0o1 天前
63、.NET 异常处理
c#·.net·异常处理