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;
    }
    //...
}
相关推荐
小码编匠20 小时前
WPF 中的高级交互通过右键拖动实现图像灵活缩放
后端·c#·.net
唐青枫1 天前
C#.NET 定时任务与队列利器:Hangfire 完整教程
c#·.net
hez20101 天前
Runtime Async - 步入高性能异步时代
c#·.net·.net core·clr
mudtools2 天前
.NET驾驭Word之力:玩转文本与格式
c#·.net
唐青枫2 天前
C#.NET 数据库开发提速秘籍:SqlSugar 实战详解
c#·.net
mudtools3 天前
.NET驾驭Word之力:理解Word对象模型核心 (Application, Document, Range)
c#·.net
大飞pkz3 天前
【设计模式】C#反射实现抽象工厂模式
设计模式·c#·抽象工厂模式·c#反射·c#反射实现抽象工厂模式
唐青枫3 天前
从入门到进阶:C#.NET Stopwatch 计时与性能测量全攻略
c#·.net
未来之窗软件服务3 天前
幽冥大陆(二)RDIFSDK 接口文档:布草洗涤厂高效运营的技术桥梁C#—东方仙盟
开发语言·c#·rdif·仙盟创梦ide·东方仙盟
1uther3 天前
Unity核心概念⑨:Screen
开发语言·游戏·unity·c#·游戏引擎