1、枚举绑定combox的ItemsSource
ItemsSource绑定的是个集合值,要想枚举绑定ItemsSource,首先应该想到的是把枚举值变成集合。

方法一:使用资源里的ObjectDataProvider
如以下枚举

public enum PeopleEnum
{
中国人,
美国人,
英国人,
俄罗斯人
}
前端绑定:

<Window x:Class="ComboxTest.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:ComboxTest"
mc:Ignorable="d"
Title="MainWindow" Height="200" Width="300">
<Window.Resources>
<ObjectDataProvider x:Key="peopleEnum" MethodName="GetValues" ObjectType="{x:Type local:PeopleEnum}">
<ObjectDataProvider.MethodParameters>
<x:Type Type="local:PeopleEnum"/>
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
</Window.Resources>
<StackPanel>
<ComboBox Margin="6" IsReadOnly="True" SelectedIndex="0" ItemsSource="{Binding Source={StaticResource peopleEnum}}"
SelectedItem="{Binding People}"></ComboBox>
<Button Margin="6" Click="show_People">显示选择项</Button>
</StackPanel>
</Window>

后端代码:

public partial class MainWindow : Window,INotifyPropertyChanged
{
    
#region 属性改变事件
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion private PeopleEnum people; public PeopleEnum People
{
get => people;
set { people = value; OnPropertyChanged("People"); }
} public MainWindow()
{
InitializeComponent();
this.DataContext = this;
} private void show_People(object sender, RoutedEventArgs e)
{
MessageBox.Show(People.ToString());
}
}

方法二:使用EnumerationExtension

有时候公司对编码有要求,比如枚举不能用中文,中文需要写到Description里。

重写一下上面的例子:

public enum PeopleEnum
{
[Description("中国人")]
CHINESE,
[Description("美国人")]
AMERICAN,
[Description("英国人")]
ENGLISHMAN,
[Description("俄罗斯人")]
RUSSIAN
}
然后写个枚举拓展的类:

public class EnumerationExtension : MarkupExtension
{
private Type _enumType; public EnumerationExtension(Type enumType)
{
if (enumType == null)
throw new ArgumentNullException("enumType"); EnumType = enumType;
} public Type EnumType
{
get { return _enumType; }
private set
{
if (_enumType == value)
return; var enumType = Nullable.GetUnderlyingType(value) ?? value; if (enumType.IsEnum == false)
throw new ArgumentException("Type must be an Enum."); _enumType = value;
}
} public override object ProvideValue(IServiceProvider serviceProvider)
{
var enumValues = Enum.GetValues(EnumType); return (
from object enumValue in enumValues
select new EnumerationMember
{
Value = enumValue,
Description = GetDescription(enumValue)
}).ToArray();
} private string GetDescription(object enumValue)
{
var descriptionAttribute = EnumType
.GetField(enumValue.ToString())
.GetCustomAttributes(typeof(DescriptionAttribute), false)
.FirstOrDefault() as DescriptionAttribute; return descriptionAttribute != null
? descriptionAttribute.Description
: enumValue.ToString();
} public class EnumerationMember
{
public string Description { get; set; }
public object Value { get; set; }
}
}

前端使用:

<ComboBox Grid.Row="0" Grid.Column="1" Margin="3" MinHeight="28"
ItemsSource="{Binding Source={local:Enumeration {x:Type local:PeopleEnum}}}"
DisplayMemberPath="Description" SelectedValue="{Binding People}" SelectedValuePath="Value">
</ComboBox>

这样写代码会简洁很多。

2、布尔值绑定combox的ItemsSource

思路是先有个对应布尔值的枚举,然后用转换器进行转换。

public enum BoolEnum
{
是,

}

public class BoolEnumConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if ((bool)value == true)
return BoolEnum.是;
else
return BoolEnum.否;
} public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
if ((BoolEnum)value == BoolEnum.是)
return true;
else
return false;
}
}

前端代码:

<Window x:Class="ComboxTest.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:ComboxTest"
mc:Ignorable="d"
Title="MainWindow" Height="200" Width="300">
<Window.Resources>
<ObjectDataProvider x:Key="boolEnum" MethodName="GetValues" ObjectType="{x:Type local:BoolEnum}">
<ObjectDataProvider.MethodParameters>
<x:Type Type="local:BoolEnum"/>
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
<local:BoolEnumConverter x:Key="boolEnumConverter" />
</Window.Resources>
<StackPanel>
<ComboBox IsReadOnly="True" Margin="6" SelectedIndex="0" ItemsSource="{Binding Source={StaticResource boolEnum}}"
SelectedItem="{Binding YesOrNo,Converter={StaticResource boolEnumConverter}}"></ComboBox>
<Button Margin="6" Click="show_result">显示选择项</Button>
</StackPanel>
</Window>

  

public partial class MainWindow : Window,INotifyPropertyChanged
{
#region 属性改变事件
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion private bool yesOrNo=true; public bool YesOrNo
{
get => yesOrNo;
set { yesOrNo = value; OnPropertyChanged("YesOrNo"); }
} public MainWindow()
{
InitializeComponent();
this.DataContext = this;
} private void show_result(object sender, RoutedEventArgs e)
{
MessageBox.Show(YesOrNo.ToString());
}
}

  

原文链接:https://blog.csdn.net/niuge8905/article/details/112647213

WPF中向下拉框中绑定枚举体的更多相关文章

  1. 在HTML中的下拉框中怎样实现超连接?

    给你个例子自己改吧: <SELECT name="select" onchange="window.open(this.options[this.selectedI ...

  2. 利用js取到下拉框中选择的值

    现在的需求是:下拉框中要是选择加盟商让其继续选择学校,要是选择平台管理员则不需要选择学校.隐藏选择下拉列表. 选择枚举值: /// <summary> /// 平台角色 /// </ ...

  3. Excel中添加下拉框

    数据->数据验证->数据验证 设置—>允许下拉框中选择序列,来源中写下拉选项,每个选项之间用逗号隔开

  4. 让下拉框中同时显示Key与Value

    声明:原创作品,转载时请注明文章来自SAP师太技术博客( 博/客/园www.cnblogs.com):www.cnblogs.com/jiangzhengjun,并以超链接形式标明文章原始出处,否则将 ...

  5. jquery选中将select下拉框中一项后赋值给text文本框

    jquery选中将select下拉框中一项后赋值给text文本框,出现无法将第一个下拉框的value赋值给文本框 因为select默认选中第一项..在选择第一项时,便导致无法激发onchange事件. ...

  6. 快速解决js开发下拉框中blur与click冲突

    在开发中我们会经常遇到blur和click冲突的情况.下面叙述了开发中常遇到的"下拉框"的问题,并提供了两种解决方案. 一.blur和click事件简述 blur事件:当元素失去焦 ...

  7. 选择屏幕中的下拉框和dialog中下拉框设计

    REPORT  YTEST014. PARAMETERS: auart LIKE vapma-auart  AS LISTBOX   VISIBLE LENGTH 6. AT SELECTION-SC ...

  8. JavaScript向select下拉框中加入和删除元素

    JavaScript向select下拉框中加入和删除元素 1.说明 a   利用append()方法向下拉框中加入元素 b   利用remove()方法移除下拉框中最后一个元素 2.设计源代码 < ...

  9. Ajax实现在textbox中输入内容,动态从数据库中模糊查询显示到下拉框中

    功能:在textbox中输入内容,动态从数据库模糊查询显示到下拉框中,以供选择 1.建立一aspx页面,html代码 <HTML> <HEAD> <title>We ...

  10. JavaScript向select下拉框中添加和删除元素

    JavaScript向select下拉框中添加和删除元素 1.说明 a   利用append()方法向下拉框中添加元素 b   利用remove()方法移除下拉框中最后一个元素 2.设计源码 < ...

随机推荐

  1. JVM(一) --- 什么是JVM

    写在文章前:本系列博客是学习黑马程序员JVM完整教程所做笔记.若有错误希望大佬们评论区修正. 一.什么是JVM      Java Virtual Machine - java程序运行时所需环境(ja ...

  2. go-fastdfs断点续传功能

    1)安装go-fastdfs: 可以从GitHub上获取go-fastdfs的源码,然后使用go get命令安装: go get github.com/sjqzhang/go-fastdfs 2)安装 ...

  3. PHP_工厂模式

    实例化类,先需要引入类文件,但是有时候我们并不知道可能要用到那些类,如果将所有类文件全部引入,会造成资源浪费,这时候可以采用工厂模式,专门用于 自动加载.实例化 类. 实例代码: 注:案例中假设有一个 ...

  4. SQL server自动创建日历表。

    做日报功能需要统计每个月的上班天数,节假日因为每年的日期都不一样,所以需要自己手动更新这些节假日 1:首先先自动创建一个日历表,选择开始年月日和结束的年月日 不要同时执行,先执行创建表之后CREATE ...

  5. 12组-Beta冲刺-4/5

    一.基本情况 队名:字节不跳动 组长博客:https://www.cnblogs.com/147258369k/p/15604454.html Github链接:https://github.com/ ...

  6. hadoop集群搭建之测试集群,配置历史服务器,日志聚集,时间同步

    hadoop集群搭建之测试集群,配置历史服务器,日志聚集,时间同步前期概要:我们完全分布式集群已经搭建完毕,并且还写了群启/群关的脚本, 接下来有必要来测试一遍集群,我们可以使用官方的案例,用它们在集 ...

  7. undefined reference to symbol xxxxx和undefined symbol:xxxx错误的原因分析以及解决方法

    Linux下编译程序时,经常会遇到"undefined reference to XXX" 报错,或者运行时出现undefined symbol:xxxx报错. 这里总结一些可能的 ...

  8. synchronized与CAS

    参考:java3y<对线面试官> synchronized synchronized是⼀种互斥锁,⼀次只能允许⼀个线程进⼊被锁住的代码块synchronized是Java的⼀个关键字,它能 ...

  9. debian11下载软件包及依赖(本地使用)

    记录下实践情况,原文: https://blog.csdn.net/zgp210317/article/details/120586189?spm=1001.2101.3001.6650.2& ...

  10. 阿里云centos7安装图形界面gnome

    这应该是很无聊很蛇精的操作吧. 首先命令行远程登陆阿里云,然后root身份更新系统,安装gnome这些操作(菜如我以前都没有操作过),参照网上虚拟机的教程. # yum update -y # yum ...