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;
    }
}

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

相关推荐
weixin_4471035819 分钟前
Wpf布局之StackPanel!
wpf
小老鼠爱大米21 分钟前
[C#] WPF - 资源URI
c#·wpf·uri
三千道应用题8 小时前
WPF学习笔记(13)列表框控件ListBox与数据模板
wpf
阿蒙Amon9 天前
《C#图解教程 第5版》深度推荐
开发语言·c#
暖馒9 天前
C#委托与事件的区别
开发语言·c#
JosieBook9 天前
【C#】C#异步编程:异步延时 vs 阻塞延时深度对比
c#·多线程·异步·阻塞
甄天9 天前
WPF中MVVM和MVVMLight模式
c#·wpf·visual studio
冰茶_10 天前
ASP.NET Core API文档与测试实战指南
后端·学习·http·ui·c#·asp.net
_oP_i10 天前
实现 “WebView2 获取word选中内容
开发语言·c#·word
Kookoos10 天前
ABP vNext + Azure Application Insights:APM 监控与性能诊断最佳实践
后端·c#·.net·abp vnext