WPF基础(1.1):ComboBox的使用

本篇文章介绍ComboBox的基本使用。

本篇文章的例子实现的功能:后端获取前端复选框中的选项之后,点击"确定"按钮,弹出一个MessageBox,显示用户选择的选项。

文章目录

  • [1. 效果展示](#1. 效果展示)
  • [2. 代码逻辑](#2. 代码逻辑)
    • [2.1 前端代码](#2.1 前端代码)
    • [2.2 后端代码](#2.2 后端代码)

1. 效果展示

先来看一下实现的效果:

第三张图显示了点击确定按钮之后的效果。

2. 代码逻辑

2.1 前端代码

文件名:MainWindow.xaml

csharp 复制代码
<Window x:Class="ComboBox.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:ComboBox"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="192*"/>
            <ColumnDefinition/>
            <ColumnDefinition Width="9*"/>
            <ColumnDefinition Width="598*"/>
        </Grid.ColumnDefinitions>
        <!-- ComboBox 用来显示选择项 -->
        <ComboBox x:Name="MyComboBox" HorizontalAlignment="Left" VerticalAlignment="Top" Width="200" Height="30" Margin="10,10,0,0" 
                  SelectionChanged="ComboBox_SelectionChanged" Grid.ColumnSpan="4" >
            <ComboBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <!-- 复选框,绑定每个项的选中状态 -->
                        <CheckBox IsChecked="{Binding Path=IsChecked}" Background="#409eff" />
                        <TextBlock Text="{Binding Path=LogTypeString}" Foreground="BlueViolet"/>
                    </StackPanel>
                </DataTemplate>
            </ComboBox.ItemTemplate>
        </ComboBox>

        <!-- 一个确定按钮 -->
        <Button Grid.Column="0" Content="确定" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Height="30" Margin="10,50,0,0" Click="OnConfirmButtonClick" />

        <!-- 用来显示用户选中的复选框项 -->
        <TextBlock x:Name="SelectedValuesTextBlock" HorizontalAlignment="Left" VerticalAlignment="Top" Width="300" Height="30" Margin="10,100,0,0" Grid.ColumnSpan="4"
                   Grid.Column="0"
                   Background="Aqua"
                   />
    </Grid>
</Window>

代码简要分析:

  1. 在前端中,通过x:Name命名的控件对应的后端代码当中可以直接访问这些控件对象。例如,TextBlock控件的x:NameSelectedValuesTextBlock,那么在对应cs文件中,直接可以通过SelectedValuesTextBlock访问控件的属性。
  2. CheckBox控件的IsChecked属性绑定到了LogTypeItem类的IsChecked字段。

2.2 后端代码

文件名:MainWindow.xaml.cs

csharp 复制代码
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace ComboBox
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            LoadComboBoxItems();
        }

        // 模拟从后端获取数据来填充 ComboBox 选项
        private void LoadComboBoxItems()
        {
            // 假设这些是从后端获取的选项
            List<LogTypeItem> comboBoxItems =
            [
                new("Option 1", false),
                new("Option 2", false),
                new("Option 3", false),
                new("Option 4", false)
            ];

            // 设置 ComboBox 的数据源
            MyComboBox.ItemsSource = comboBoxItems;
        }


        // 确定按钮点击事件处理程序
        private void OnConfirmButtonClick(object sender, RoutedEventArgs e)
        {
            // 获取所有选中的复选框项
            List<string> selectedItems = new();

            // 遍历 ComboBox 中的项
            foreach (var item in MyComboBox.Items)
            {
                // 如果复选框被选中,添加到 selectedItems 列表
                if (item is LogTypeItem logTypeItem && logTypeItem.IsChecked)
                {
                    selectedItems.Add(logTypeItem.LogTypeString);
                }
            }

            if (selectedItems.Count != 0)
            {
                // 显示所选的项
                string selectedValues = string.Join(", ", selectedItems);
                SelectedValuesTextBlock.Text = "Selected Items: " + selectedValues;
                MessageBox.Show("You selected: " + selectedValues);
            }
            else
            {
                MessageBox.Show("You selected nothing!");
            }

            
        }

        private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            // 获取 ComboBox 当前选择的项

            // 如果选项不为空
            if (MyComboBox.SelectedItem is LogTypeItem selectedItem)
            {
                // 更新 TextBlock 显示选中的值
                SelectedValuesTextBlock.Text = "You selected: " + selectedItem.LogTypeString;
            }
        }
    }

    // 选项数据模型
    public class LogTypeItem(string logTypeString, bool isChecked)
    {
        public string LogTypeString { get; set; } = logTypeString;
        public bool IsChecked { get; set; } = isChecked;
    }
}

好了,本篇文章就介绍到这里。如有帮助,可以点个赞。

相关推荐
2601_9621741713 小时前
Redis 简介
数据库·redis·wpf
格林威17 小时前
C# 相机Burst模式图像采集:使用相机内存配合OpenCvSharp和Halcon实现短时间的高速采集的方法
开发语言·人工智能·数码相机·计算机视觉·c#·视觉检测·工业相机
J总裁的小芒果18 小时前
参数过多-分批传参
c#
典典分享指南18 小时前
短视频分镜提示词:让 AI 出片的产品口播
java·c#·bash·composer·symfony
Z59981784119 小时前
c#软件开发学习笔记--WPF(Canvas、数据绑定、MVVM模式、值转换器)
笔记·学习·c#
淡海水21 小时前
05-03-栈队列-PriorityQueue-TElement-TPriority-NET6优先队列语义与四叉堆实现
服务器·前端·c#·priorityqueue·clr·telement
leonkay1 天前
C# 特性(Attribute)——【1】基础讲解
开发语言·青少年编程·面试·c#·.net·个人开发
CSDN_RTKLIB1 天前
数据库七大符号表
c#
leonkay1 天前
C# 特性(Attribute)——【2】工业设备参数框架设计
经验分享·面试·架构·c#·学习方法·设计