首页 > 其他分享 >WPF中向下拉框中绑定枚举体

WPF中向下拉框中绑定枚举体

时间:2022-08-20 10:56:01浏览次数:75  
标签:return object value public 枚举 中向 WPF 下拉框 enumType

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

标签:return,object,value,public,枚举,中向,WPF,下拉框,enumType
From: https://www.cnblogs.com/jyj666/p/16607309.html

相关文章

  • eayui 下拉框点击事件
    $("#ID").combobox({onChange:function(){ if($("#ID").combobox("getValue")=="2"){ // }else{ // ......
  • WPFGroupBox控件自定义
    先上效果图  直接上代码(直接在Window.Resources里面添加这段代码)<StyleTargetType="GroupBox"><SetterProperty="Margin"Value="10,5"/>......
  • WPF将控件转为图片(Visual试图转Bitmap)
    RenderTargetBitmaptarget=newRenderTargetBitmap((int)grid.ActualWidth,(int)grid.ActualHeight,96d,96d,PixelFormats.Default);target.Render(grid);Cropped......
  • 操作栏中操作过多变为下拉框
    封装插件<template><divclass="as-more-operate"v-if="$slots.default"><el-popoverplacement="bottom"ref="morePopover"popper-class=......
  • Winform下拉框使用拼音首字母查询
    项目需要一个搜索所在单位的选项,因为选项众多需要用下拉框来进行选择。众多选择为了更好的使用,采用了拼音首字母进行查询。显示的效果如果下:在输入框输入X出现X相关的单......
  • 【WPF】命令系统
    命令四要素1、命令,一般情况都是使用”路由ui命令“2、命令源:触发命令的地方。3、命令绑定:将命令和执行方法绑定,然后在将commandbing放置在,命令目标的外围ui控件上,这样......
  • C# WPF 访问剪切板报错
    如果剪贴板操作失败(例如 HRESULT0x800401D0(CLIPBRD_E_CANT_OPEN) 错误),则会引发相应的 ExternalException (,这是一种ExternalException)。由于Win32 OpenClipbo......
  • C#-WPF-LiveChart大数据时图标绘制(曲线图)并支持图片保存
    xmlns:lvc="clr-namespace:LiveCharts.Wpf;assembly=LiveCharts.Wpf"<Button   Name="SaveBtn"   Grid.Row="0"   Width="100"   Height="32"   ......
  • element下拉框远程搜索debounce防抖控制
    一、需求:下拉框支持远程搜索,根据用户输入字符,调接口获取数据渲染到下拉列表上,供用户选择。二、为什么要做防抖控制?在做远程搜索时,如果每输入1个字就调用1次接口,就会频繁......
  • 【WPF】XDG0062 必须使“Setter.Property”具有非 null 值。
    编译环境vs2022.net6.0在样式中给附加属性设置触发条件。显示XDG0062错误,但是代码能正常编译和运行。   编辑环境中运行后,能正常运行   解决方法......