【6月日新计划25】WPF入门-ComboBox的使用

386 阅读12分钟

1. All Controls

All Controls Offcail Website: learn.microsoft.com/zh-cn/dotne…

也可以參考下面

InitializingNewItemEventArgs
AccessText

用下划线来指定用作访问键的字符。

ActivatingKeyTipEventArgs

ActivatingKeyTip 事件提供数据。

AddingNewItemEventArgs

AddingNewItem 事件提供数据。

AdornedElementPlaceholder

表示 ControlTemplate 中使用的元素,该元素用于指定修饰控件相对于 ControlTemplate 中的其他元素所放置的位置。

AlternationConverter

通过将整数作为索引应用于对象列表,进行整数和对象的相互转换。

BooleanToVisibilityConverter

表示将布尔值与 Visibility 枚举值相互转换的转换器。

Border

在另一个元素四周绘制边框和/或背景。

BorderGapMaskConverter

表示一个转换器,它将 GroupBox 控件的维度转换到 VisualBrush 中。

Button

表示 Windows 按钮控件,该按钮对 Click 事件做出反应。

Calendar

代表一个控件,此控件允许用户使用可视的日历显示来选择日期。

CalendarBlackoutDatesCollection

表示 Calendar 中的非可选日期的集合。

CalendarDateChangedEventArgs

DisplayDateChanged 事件提供数据。

CalendarDateRange

表示 Calendar 中的日期范围。

CalendarModeChangedEventArgs

DisplayModeChanged 事件提供数据。

Canvas

定义一个区域,可在其中使用相对于 Canvas 区域的坐标以显式方式来定位子元素。

CheckBox

表示用户可以选择和清除的控件。

CleanUpVirtualizedItemEventArgs

CleanUpVirtualizedItem 事件提供数据。

ColumnDefinition

定义将应用于 Grid 元素的特定于列的属性。

ColumnDefinitionCollection

提供对 ColumnDefinition 对象的有序强类型集合的访问。

ComboBox

表示带有下拉列表的选择控件,通过单击控件上的箭头可显示或隐藏下拉列表。

ComboBoxItem

ComboBox 内实现可选择的项。

ContentControl

表示包含一段任意类型内容的控件。

ContentPresenter

显示 ContentControl 的内容。

ContextMenu

表示一个弹出菜单,该弹出菜单使控件能够公开特定于该控件的上下文的功能。

ContextMenuEventArgs

为上下文菜单事件提供数据。

ContextMenuService

提供用于显示 ContextMenu 的系统实现。

Control

表示用户界面 (UI) 元素的基类,这些元素使用 ControlTemplate 来定义其外观。

ControlTemplate

指定 Control 的可在其多个实例之间共享的可视结构和行为方面。

DataErrorValidationRule

表示一个规则,该规则检查由源对象的 IDataErrorInfo 实现所引发的错误。

DataGrid

表示用于在可自定义的网格中显示数据的控件。

DataGridAutoGeneratingColumnEventArgs

AutoGeneratingColumn 事件提供数据。

DataGridBeginningEditEventArgs

BeginningEdit 事件提供数据。

DataGridBoundColumn

用作列的基类,这些列可绑定到 DataGrid 的数据源中的属性。

DataGridCell

表示 DataGrid 控件的单元格。

DataGridCellClipboardEventArgs

提供有关 CopyingCellClipboardContentPastingCellClipboardContent 事件的数据。

DataGridCellEditEndingEventArgs

CellEditEnding 事件提供数据。

DataGridCellsPanel

表示一个面板,该面板在数据网格中对单元格和列标题进行布局。

DataGridCheckBoxColumn

表示一个 DataGrid 列,该列在其单元格中承载 CheckBox 控件。

DataGridColumn

表示一个 DataGrid 列。

DataGridColumnEventArgs

提供有关 ColumnDisplayIndexChangedColumnReordered 事件的数据。

DataGridColumnReorderingEventArgs

ColumnReordering 事件提供数据。

DataGridComboBoxColumn

表示一个 DataGrid 列,该列在其单元格中承载 ComboBox 控件。

DataGridHyperlinkColumn

表示一个 DataGrid 列,该列在其单元格中承载 Uri 元素。

DataGridLengthConverter

DataGridLength 类的实例与各种类型的实例之间进行转换。

DataGridPreparingCellForEditEventArgs

PreparingCellForEdit 事件提供数据。

DataGridRow

表示一个 DataGrid 行。

DataGridRowClipboardEventArgs

CopyingRowClipboardContent 事件提供数据。

DataGridRowDetailsEventArgs

LoadingRowDetailsUnloadingRowDetailsRowDetailsVisibilityChanged 事件提供数据。

DataGridRowEditEndingEventArgs

RowEditEnding 事件提供数据。

DataGridRowEventArgs

提供有关 LoadingRowUnloadingRow 事件的数据。

DataGridSortingEventArgs

Sorting 事件提供数据。

DataGridTemplateColumn

表示一个 DataGrid 列,该列在其单元格中承载模板指定的内容。

DataGridTextColumn

表示一个 DataGrid 列,该列在其单元格中承载文本内容。

DataTemplateSelector

提供一种方式,用于根据数据对象和数据绑定元素来选择 DataTemplate

DatePicker

表示一个允许用户选择日期的控件。

DatePickerDateValidationErrorEventArgs

DateValidationError 事件提供数据。

Decorator

提供在单个子元素(如 BorderViewbox)上或周围应用效果的元素的基类。

DefinitionBase

定义支持 ColumnDefinitionCollectionRowDefinitionCollection 类使用的共享大小组所需的功能。 这是一个抽象类。

DockPanel

定义一个区域,从中可以按相对位置水平或垂直排列各个子元素。

DocumentViewer

表示一个文档查看控件,该控件可以承载分页的 FixedDocument 内容,例如 XpsDocument

ExceptionValidationRule

表示用于检查绑定源属性更新过程中抛出的异常的规则。

Expander

表示一种控件,该控件显示具有可折叠内容显示窗口的标题。

FlowDocumentPageViewer

表示一种控件,该控件以固定查看模式查看流内容(一次显示一页内容)。

FlowDocumentReader

提供一种查看流内容的控件,该控件内置了对多种查看模式的支持。

FlowDocumentScrollViewer

提供一种控件,该控件以连续滚动模式查看流内容。

Frame

框架是一种支持导航的内容控件。

Grid

定义由列和行组成的灵活的网格区域。

GridSplitter

表示重新分布 Grid 控件的列间距或行间距的控件。

GridView

表示 ListView 控件的以列形式显示数据项的视图模式。

GridViewColumn

表示显示数据的列。

GridViewColumnCollection

表示 GridViewColumn 对象集合。

GridViewColumnHeader

表示 GridViewColumn 的列标题。

GridViewHeaderRowPresenter

表示定义列标题的行布局所用的对象。

GridViewRowPresenter

表示指定数据的行布局所用的对象。

GroupBox

表示一个控件,该控件用于创建具有用户界面 (UI) 内容边框和标题的容器。

GroupItem

显示为组生成的可视子树的根。

GroupStyle

定义希望组查看每个级别的方式。

HeaderedContentControl

为包含单项内容并具有标头的所有控件提供基实现。

HeaderedItemsControl

表示包含多个项并且具有标题的控件。

Image

表示用于显示图像的控件。

InitializingNewItem 事件提供数据。

InkCanvas

定义接收和显示墨迹笔划的区域。

InkCanvasGestureEventArgs

Gesture 事件提供数据。

InkCanvasSelectionChangingEventArgs

SelectionChanging 提供数据。

InkCanvasSelectionEditingEventArgs

提供有关 SelectionMovingSelectionResizing 事件的数据。

InkCanvasStrokeCollectedEventArgs

StrokeCollected 事件提供数据。

InkCanvasStrokeErasingEventArgs

StrokeErasing 事件提供数据。

InkCanvasStrokesReplacedEventArgs

StrokesReplaced 事件提供数据。

InkPresenter

在图面上呈现墨迹。

ItemCollection

包含构成 ItemsControl 的内容的项的列表。

ItemContainerGenerator

代表主机主机生成用户界面 (UI),例如 ItemsControl

ItemContainerTemplate

提供模板以为 ItemsControl 对象生产容器。

ItemContainerTemplateKey

ItemContainerTemplate 对象提供源键。

ItemContainerTemplateSelector

使您能够在 ItemContainerTemplate 中为每个项选择 ItemsControl

ItemsControl

表示可用于呈现一组项的控件。

ItemsPanelTemplate

指定 ItemsPresenterItemsControl 的项的布局创建的面板。

ItemsPresenter

在项控件的模板中使用,用于指定要将 ItemsPanel 定义的 ItemsControl 添加到控件的可视化树中的什么位置。

KeyTipAccessedEventArgs

KeyTipAccessed 事件提供数据。

KeyTipControl

表示在 KeyTip 内部使用的控件。

KeyTipService

表示提供属性、方法和事件以在 WPF Ribbon 控件中启用并管理快捷键提示的服务。

Label

表示控件的文本标签,并提供访问密钥支持。

ListBox

包含可选项列表。

ListBoxItem

表示 ListBox 中的可选项。

ListView

表示用于显示数据项列表的控件。

ListViewItem

表示 ListView 控件中的一个项。

MediaElement

表示包含音频和/或视频的控件。

Menu

表示一个 Windows 菜单控件,该控件可用于按层次组织与命令和事件处理程序关联的元素。

MenuItem

表示 Menu 内某个可选择的项。

MenuScrollingVisibilityConverter

表示用于处理滚动菜单中重复按钮的可见性的数据绑定转换器。

NotifyDataErrorValidationRule

表示一个规则,该规则检查由源对象的 INotifyDataErrorInfo 实现所引发的错误。

Page

封装一页可由 Windows Internet Explorer、NavigationWindowFrame 导航到和承载的内容。

Panel

为所有 Panel 元素提供基类。 使用 Panel 元素放置和排列 Windows Presentation Foundation (WPF) 应用程序中的子对象。

PasswordBox

表示用于输入和处理密码的控件。

PrintDialog

调用标准的 Microsoft Windows 打印对话框,此对话框可根据用户输入配置 PrintTicketPrintQueue,然后打印文档。

PrintDialogException

当在打开、访问或使用一个 PrintDialog 的过程中发生错误情况时引发的异常。

ProgressBar

指示操作进度。

RadioButton

表示可由用户选择但不能清除的按钮。 可以通过单击来设置 IsCheckedRadioButton 属性,但只能以编程方式清除该属性。

RichTextBox

表示对 FlowDocument 对象进行操作的丰富编辑控件。

RowDefinition

定义将应用于 Grid 元素的特定于行的属性。

RowDefinitionCollection

提供对 RowDefinition 对象的有序强类型集合的访问。

ScrollChangedEventArgs

描述了滚动状态的更改,并包括 ScrollChanged 事件的必需自变量。

ScrollContentPresenter

显示 ScrollViewer 控件的内容。

ScrollViewer

表示可包含其他可视元素的可滚动区域。

SelectedCellsChangedEventArgs

SelectedCellsChanged 事件提供数据。

SelectedDatesCollection

表示 Calendar 中一组选中的日期。

SelectionChangedEventArgs

SelectionChanged 事件提供数据。

Separator

用于分隔项控件中各个项的控件。

Slider

表示一个控件,该控件可让用户通过沿 Thumb 移动 Track 控件从一个值范围中进行选择。

SoundPlayerAction

表示用于播放 .wav 文件的轻量音频播放 TriggerAction

SpellCheck

为文本编辑控件(如 TextBoxRichTextBox)提供实时拼写检查功能。

SpellingError

表示编辑控件(即 TextBoxRichTextBox)中拼写错误的单词。

StackPanel

将子元素排列成水平或垂直的一行。

StickyNoteControl

表示一个控件,该控件允许用户在文档中附加键入的文本或手写的批注。

StyleSelector

提供根据自定义逻辑应用样式的方法。

TabControl

表示包含多个项的控件,这些项共享屏幕上的同一空间。

TabItem

表示 TabControl 内某个可选择的项。

TextBlock

提供一个轻型控件,用于显示少量流内容。

TextBox

表示一个控件,该控件可用于显示或编辑无格式文本。

TextChange

包含有关在 TextChanged 事件中发生的更改的信息。

TextChangedEventArgs

TextChanged 事件提供数据。

TextSearch

使用户能够通过键入字符串的前缀来快速访问组中的项。

ToolBar

为一组命令或控件提供容器。

ToolBarTray

表示处理 ToolBar 的布局的容器。

ToolTip

表示一个控件,该控件可创建一个弹出窗口,以便在界面中显示元素的信息。

ToolTipEventArgs

为在工具提示打开或关闭时发生的事件提供事件信息。

ToolTipService

表示一项服务,该服务提供用于控制工具提示的显示和行为的属性和事件。

TreeView

表示一个控件,该控件在树结构(其中的项可以展开和折叠)中显示分层数据。

TreeViewItem

TreeView 控件中实现可选择的项。

UIElementCollection

表示 UIElement 子元素的有序集合。

UserControl

提供一种创建控件的简单方法。

Validation

提供支持数据验证的方法和附加属性。

ValidationError

表示一个验证错误,该错误在 ValidationRule 报告验证错误时由绑定引擎创建,或者通过 MarkInvalid(BindingExpressionBase, ValidationError) 方法显式创建。

ValidationErrorEventArgs

提供 Error 附加事件的相关信息。

ValidationResult

表示 由 ValidationRule方法Validate(Object, CultureInfo) 返回的结果,该结果指示检查的值是否传递 了 ValidationRule

ValidationRule

提供创建自定义规则的一个方式,旨在检查用户输入的有效性。

ViewBase

表示定义 ListView 控件中数据外观的视图的基类。

Viewbox

定义一个内容修饰器,以便拉伸或缩放单一子项使其填满可用的控件。

Viewport3D

呈现 Viewport3D 元素的 2-D 布局范围内包含的 3-D 内容。

VirtualizationCacheLengthConverter

在对象和 VirtualizationCacheLength 之间来回转换。

VirtualizingPanel

为虚拟化其子数据集合的 Panel 元素提供一个框架。 这是一个抽象类。

VirtualizingStackPanel

在水平或垂直的一行中排列并显示内容。

WebBrowser

承载 HTML 文档并在其之间导航。 启用 WPF 托管代码和 HTML 脚本之间的互操作性。

WrapPanel

按从左到右的顺序位置定位子元素,在包含框的边缘处将内容切换到下一行。 后续排序按照从上至下或从右至左的顺序进行,具体取决于 Orientation 属性的值。

2. ComboBox

learn.microsoft.com/zh-cn/dotne…

nameValue
IsEditable获取或设置一个值,该值指示启用或禁用 ComboBox 的文本框中的文本编辑。
IsEnabled获取或设置一个值,该值指示是否 用户界面 (UI) 中启用此元素。 这是依赖项属性。(继承自 UIElement)
SelectedIndex获取或设置当前选择中第一项的索引,如果选择为空,则返回负一(-1)。(继承自 Selector)
SelectedItem获取或设置当前选择中的第一项,或者,如果选择为空,则返回 null。(继承自 Selector)
SelectedValue获获取或设置通过使用 SelectedItem 而获取的 SelectedValuePath 的值。(继承自 Selector)
SelectedValuePath获取或设置用于从 SelectedValue 获取 SelectedItem 的路径。(继承自 Selector)
Text获取或设置当前选定项的文本。

2.1 xaml

此處使用的是Prism的Mvvm模式和MaterialDesign樣式

<UserControl x:Class="BlankApp1.Views.Practice.ComboBoxView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:local="clr-namespace:BlankApp1.Views.Practice"
             xmlns:i="http://schemas.microsoft.com/xaml/behaviors"
             xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
             xmlns:prism="http://prismlibrary.com/"
             mc:Ignorable="d"
             d:DesignHeight="450"
             d:DesignWidth="800">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <DockPanel LastChildFill="False">

            <ComboBox x:Name="PalletModeComboBox"
                      Margin="30,0,0,0"
                      Width="150"
                      Height="50"
                      VerticalAlignment="Center"
                      SelectedValue="{Binding SelectedModeCode,Mode=TwoWay}"
                      SelectedValuePath="Content"
                      HorizontalAlignment="Left"
                      SelectedIndex="{Binding ComboBoxIndex,Mode=TwoWay}"
                      Style="{StaticResource MaterialDesignOutlinedComboBox}">
                <ComboBoxItem Content="model"
                              Tag="1"></ComboBoxItem>
                <ComboBoxItem Content="mode2"
                              Tag="2"></ComboBoxItem>
                <ComboBoxItem Content="mode3"
                              Tag="3"></ComboBoxItem>
                <ComboBoxItem Content="mode4"
                              Tag="4"></ComboBoxItem>
                <ComboBoxItem Content="mode5"
                              Tag="5"></ComboBoxItem>
                <ComboBoxItem Content="mode6"
                              Tag="6"></ComboBoxItem>
                <i:Interaction.Triggers>
                    <i:EventTrigger EventName="SelectionChanged">
                        <prism:InvokeCommandAction Command="{Binding ModeChangedCommand}" />
                    </i:EventTrigger>
                </i:Interaction.Triggers>
            </ComboBox>
            <Button DockPanel.Dock="Right"
                    Command="{Binding ShowMsg}"
                    Margin="3">
                <StackPanel Orientation="Horizontal">
                    <materialDesign:PackIcon Kind="AlertDecagram"
                                             Margin="3" />
                    <TextBlock Text="確定"
                               Margin="3" />
                </StackPanel>
            </Button>
            <Button DockPanel.Dock="Right"
                    Command="{Binding ShowMsg2}"
                    Margin="3">
                <StackPanel Orientation="Horizontal">
                    <materialDesign:PackIcon Kind="AlertDecagram"
                                             Margin="3" />
                    <TextBlock Text="取消"
                               Margin="3" />
                </StackPanel>
            </Button>
        </DockPanel>
    </Grid>
</UserControl>

2.2 Code

如果想設定初始值,直接給index賦值就好了。

using Prism.Commands;
using Prism.Mvvm;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BlankApp1.ViewModels.Practice
{
    public class ComboBoxViewModel : BindableBase
    {
        /// <summary>
        /// 下拉的選值
        /// </summary>
        private string selectedModeCode;
        public string SelectedModeCode
        {
            get => selectedModeCode;
            set => SetProperty(ref selectedModeCode, value);
        }

        /// <summary>
        /// 下拉的索引
        /// </summary>
        private int comboBoxIndex;

        public int ComboBoxIndex
        {
            get { return comboBoxIndex; }
            set { comboBoxIndex = value; }
        }

        public DelegateCommand ModeChangedCommand { get; private set; }

        public DelegateCommand ShowMsg { get; private set; }

        public DelegateCommand ShowMsg2 { get; private set; }
        public ComboBoxViewModel()
        {
            ComboBoxIndex = 0;
            ModeChangedCommand = new DelegateCommand(ModeCommand);
            ShowMsg = new DelegateCommand(() => {
                
                System.Diagnostics.Trace.WriteLine("---------ComboBox Select Value : " + SelectedModeCode);
                System.Diagnostics.Trace.WriteLine("---------ComboBox Select Index : " + ComboBoxIndex);
            });
            ShowMsg2 = new DelegateCommand(() =>
            {
                System.Diagnostics.Trace.WriteLine("this is a cancel button");
            });
        }

        private void ModeCommand()
        {
            
            System.Diagnostics.Trace.WriteLine("---------ComboBox Select Value : " + SelectedModeCode);
            System.Diagnostics.Trace.WriteLine("---------ComboBox Select Index : " + ComboBoxIndex);

        }

    }
}