我试图找到一个简单的例子,枚举显示为是。我所看到的所有示例都试图添加好看的显示字符串,但我不想要那种复杂性。
基本上,我有一个类,通过首先将DataContext设置为这个类,然后在xaml文件中指定绑定,保存我绑定的所有属性:
<ComboBox ItemsSource="{Binding Path=EffectStyle}"/>
但这不会在组合框中显示枚举值作为项。
我试图找到一个简单的例子,枚举显示为是。我所看到的所有示例都试图添加好看的显示字符串,但我不想要那种复杂性。
基本上,我有一个类,通过首先将DataContext设置为这个类,然后在xaml文件中指定绑定,保存我绑定的所有属性:
<ComboBox ItemsSource="{Binding Path=EffectStyle}"/>
但这不会在组合框中显示枚举值作为项。
您需要在枚举中创建一个值的数组,可以通过调用system . enumn . getvalues()来创建,并将您想要的项的枚举的Type传递给它。
如果您为ItemsSource属性指定了这一点,那么它应该用枚举的所有值填充。您可能希望将SelectedItem绑定到EffectStyle(假设它是相同枚举的属性,并且包含当前值)。
你可以通过在Window Loaded事件处理程序中放置以下代码来做到这一点,例如:
yourComboBox.ItemsSource = Enum.GetValues(typeof(EffectStyle)).Cast<EffectStyle>();
如果你需要在XAML中绑定它,你需要使用ObjectDataProvider创建可用的对象作为绑定源:
<Window x:Class="YourNamespace.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:System="clr-namespace:System;assembly=mscorlib"
xmlns:StyleAlias="clr-namespace:Motion.VideoEffects">
<Window.Resources>
<ObjectDataProvider x:Key="dataFromEnum" MethodName="GetValues"
ObjectType="{x:Type System:Enum}">
<ObjectDataProvider.MethodParameters>
<x:Type TypeName="StyleAlias:EffectStyle"/>
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
</Window.Resources>
<Grid>
<ComboBox ItemsSource="{Binding Source={StaticResource dataFromEnum}}"
SelectedItem="{Binding Path=CurrentEffectStyle}" />
</Grid>
</Window>
请注意下面的代码:
xmlns:System="clr-namespace:System;assembly=mscorlib"
xmlns:StyleAlias="clr-namespace:Motion.VideoEffects"
指导如何映射可以在MSDN上读取的命名空间和程序集。
我喜欢在ViewModel中绑定定义的所有对象,所以我尽量避免在xaml中使用<ObjectDataProvider>。
我的解决方案不使用视图中定义的数据,也不使用隐藏代码。只有一个DataBinding,一个可重用的ValueConverter,一个用于获取任意Enum类型的描述集合的方法,以及ViewModel中要绑定的单个属性。
当我想将一个Enum绑定到一个组合框时,我想要显示的文本永远不匹配Enum的值,所以我使用[Description()]属性(from System.ComponentModel)给它我实际上想在组合框中看到的文本。如果我有一周中的一天,它看起来会像这样:
public enum DayOfWeek
{
// add an optional blank value for default/no selection
[Description("")]
NOT_SET = 0,
[Description("Sunday")]
SUNDAY,
[Description("Monday")]
MONDAY,
...
}
首先,我创建了一个helper类,其中包含几个处理枚举的方法。一个方法获取一个特定值的描述,另一个方法获取一个类型的所有值及其描述。
public static class EnumHelper
{
public static string Description(this Enum value)
{
var attributes = value.GetType().GetField(value.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attributes.Any())
return (attributes.First() as DescriptionAttribute).Description;
// If no description is found, the least we can do is replace underscores with spaces
// You can add your own custom default formatting logic here
TextInfo ti = CultureInfo.CurrentCulture.TextInfo;
return ti.ToTitleCase(ti.ToLower(value.ToString().Replace("_", " ")));
}
public static IEnumerable<ValueDescription> GetAllValuesAndDescriptions(Type t)
{
if (!t.IsEnum)
throw new ArgumentException($"{nameof(t)} must be an enum type");
return Enum.GetValues(t).Cast<Enum>().Select((e) => new ValueDescription() { Value = e, Description = e.Description() }).ToList();
}
}
接下来,我们创建一个ValueConverter。从MarkupExtension继承使它更容易在XAML中使用,因此我们不必将其声明为资源。
[ValueConversion(typeof(Enum), typeof(IEnumerable<ValueDescription>))]
public class EnumToCollectionConverter : MarkupExtension, IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return EnumHelper.GetAllValuesAndDescriptions(value.GetType());
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return null;
}
public override object ProvideValue(IServiceProvider serviceProvider)
{
return this;
}
}
我的ViewModel只需要1个属性,我的视图可以绑定到组合框的SelectedValue和ItemsSource:
private DayOfWeek dayOfWeek;
public DayOfWeek SelectedDay
{
get { return dayOfWeek; }
set
{
if (dayOfWeek != value)
{
dayOfWeek = value;
OnPropertyChanged(nameof(SelectedDay));
}
}
}
最后绑定ComboBox视图(在ItemsSource绑定中使用ValueConverter)…
<ComboBox ItemsSource="{Binding Path=SelectedDay, Converter={x:EnumToCollectionConverter}, Mode=OneTime}"
SelectedValuePath="Value"
DisplayMemberPath="Description"
SelectedValue="{Binding Path=SelectedDay, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
要实现这个解决方案,你只需要复制我的EnumHelper类和EnumToCollectionConverter类。它们可以处理任何枚举。同样,我没有在这里包括它,但ValueDescription类只是一个简单的类,具有两个公共对象属性,一个叫Value,一个叫Description。您可以自己创建,或者您可以更改代码使用Tuple<object, object>或KeyValuePair<object, object>
对于那些想要查看ValueDescription类的人:
public class ValueDescription
{
public object Value {get; set};
public object Description {get; set};
}
Nick的回答确实帮助了我,但我意识到它可以稍微调整一下,以避免额外的类ValueDescription。 我记得框架中已经存在一个KeyValuePair类,所以可以使用这个代替。
代码只发生了轻微的变化:
public static IEnumerable<KeyValuePair<string, string>> GetAllValuesAndDescriptions<TEnum>() where TEnum : struct, IConvertible, IComparable, IFormattable
{
if (!typeof(TEnum).IsEnum)
{
throw new ArgumentException("TEnum must be an Enumeration type");
}
return from e in Enum.GetValues(typeof(TEnum)).Cast<Enum>()
select new KeyValuePair<string, string>(e.ToString(), e.Description());
}
public IEnumerable<KeyValuePair<string, string>> PlayerClassList
{
get
{
return EnumHelper.GetAllValuesAndDescriptions<PlayerClass>();
}
}
最后是XAML:
<ComboBox ItemSource="{Binding Path=PlayerClassList}"
DisplayMemberPath="Value"
SelectedValuePath="Key"
SelectedValue="{Binding Path=SelectedClass}" />
我希望这对其他人有所帮助。
我使用MarkupExtension的另一种解决方案。
I made class which provides items source: public class EnumToItemsSource : MarkupExtension { private readonly Type _type; public EnumToItemsSource(Type type) { _type = type; } public override object ProvideValue(IServiceProvider serviceProvider) { return Enum.GetValues(_type) .Cast<object>() .Select(e => new { Value = (int)e, DisplayName = e.ToString() }); } } That's almost all... Now use it in XAML: <ComboBox DisplayMemberPath="DisplayName" ItemsSource="{persons:EnumToItemsSource {x:Type enums:States}}" SelectedValue="{Binding Path=WhereEverYouWant}" SelectedValuePath="Value" /> Change 'enums:States' to your enum
如果你绑定到ViewModel上的实际枚举属性,而不是枚举的int表示,事情就变得棘手了。我发现有必要绑定到字符串表示,而不是在上述所有示例中预期的int值。
您可以通过将一个简单的文本框绑定到ViewModel上想要绑定的属性来判断是否存在这种情况。如果显示文本,则绑定到字符串。如果它显示一个数字,则绑定到该值。注意,我已经使用了两次显示,这通常是一个错误,但这是它工作的唯一方式。
<ComboBox SelectedValue="{Binding ElementMap.EdiDataType, Mode=TwoWay}"
DisplayMemberPath="Display"
SelectedValuePath="Display"
ItemsSource="{Binding Source={core:EnumToItemsSource {x:Type edi:EdiDataType}}}" />
Greg
上面所有的帖子都忽略了一个简单的技巧。可以从SelectedValue的绑定中找到如何自动地填充ItemsSource,以便您的XAML标记是正确的。
<Controls:EnumComboBox SelectedValue="{Binding Fool}"/>
例如,在ViewModel中
public enum FoolEnum
{
AAA, BBB, CCC, DDD
};
FoolEnum _Fool;
public FoolEnum Fool
{
get { return _Fool; }
set { ValidateRaiseAndSetIfChanged(ref _Fool, value); }
}
ValidateRaiseAndSetIfChanged是我的INPC钩子。你的可能不同。
EnumComboBox的实现如下所示,但首先我需要一个小助手来获取我的枚举字符串和值
public static List<Tuple<object, string, int>> EnumToList(Type t)
{
return Enum
.GetValues(t)
.Cast<object>()
.Select(x=>Tuple.Create(x, x.ToString(), (int)x))
.ToList();
}
和主类(注意,我使用ReactiveUI通过WhenAny钩子属性更改)
using ReactiveUI;
using ReactiveUI.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using System.Windows;
using System.Windows.Documents;
namespace My.Controls
{
public class EnumComboBox : System.Windows.Controls.ComboBox
{
static EnumComboBox()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(EnumComboBox), new FrameworkPropertyMetadata(typeof(EnumComboBox)));
}
protected override void OnInitialized( EventArgs e )
{
base.OnInitialized(e);
this.WhenAnyValue(p => p.SelectedValue)
.Where(p => p != null)
.Select(o => o.GetType())
.Where(t => t.IsEnum)
.DistinctUntilChanged()
.ObserveOn(RxApp.MainThreadScheduler)
.Subscribe(FillItems);
}
private void FillItems(Type enumType)
{
List<KeyValuePair<object, string>> values = new List<KeyValuePair<object,string>>();
foreach (var idx in EnumUtils.EnumToList(enumType))
{
values.Add(new KeyValuePair<object, string>(idx.Item1, idx.Item2));
}
this.ItemsSource = values.Select(o=>o.Key.ToString()).ToList();
UpdateLayout();
this.ItemsSource = values;
this.DisplayMemberPath = "Value";
this.SelectedValuePath = "Key";
}
}
}
您还需要在Generic中正确设置样式。XAML或者你的盒子不会渲染任何东西,你会抓狂的。
<Style TargetType="{x:Type local:EnumComboBox}" BasedOn="{StaticResource {x:Type ComboBox}}">
</Style>
就是这样。这显然可以扩展到支持i18n,但会使帖子更长。
public class EnumItemsConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (!value.GetType().IsEnum)
return false;
var enumName = value.GetType();
var obj = Enum.Parse(enumName, value.ToString());
return System.Convert.ToInt32(obj);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return Enum.ToObject(targetType, System.Convert.ToInt32(value));
}
}
如果您直接绑定到枚举对象模型属性,您应该使用这种Enum值转换器扩展Rogers和Greg的回答。
使用ObjectDataProvider:
<ObjectDataProvider x:Key="enumValues"
MethodName="GetValues" ObjectType="{x:Type System:Enum}">
<ObjectDataProvider.MethodParameters>
<x:Type TypeName="local:ExampleEnum"/>
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
然后绑定到静态资源:
ItemsSource="{Binding Source={StaticResource enumValues}}"
基于这篇文章
通用应用程序的工作方式似乎有点不同;它不具备全功能XAML的所有功能。对我有用的是:
我创建了一个枚举值列表作为enum(未转换为 字符串或整数),并将ComboBox ItemsSource绑定到它 然后我可以将ComboBox ItemSelected绑定到我的公共属性 枚举的类型是谁
只是为了好玩,我创建了一个小模板类来帮助解决这个问题,并将其发布到MSDN Samples页面。额外的位可以让我有选择地覆盖枚举的名称,并让我隐藏一些枚举。我的代码看起来很像Nick的(上面),我希望我能早点看到。
我喜欢汤姆。maruska的答案,但我需要支持我的模板在运行时可能遇到的任何枚举类型。为此,我必须使用绑定来指定标记扩展的类型。我从尼古拉的回答中得到了答案。anykienko提出了一个非常灵活的标记扩展,它可以在我能想到的任何情况下工作。它是这样消耗的:
<ComboBox SelectedValue="{Binding MyEnumProperty}"
SelectedValuePath="Value"
ItemsSource="{local:EnumToObjectArray SourceEnum={Binding MyEnumProperty}}"
DisplayMemberPath="DisplayName" />
上面引用的混合标记扩展的源代码:
class EnumToObjectArray : MarkupExtension
{
public BindingBase SourceEnum { get; set; }
public override object ProvideValue(IServiceProvider serviceProvider)
{
IProvideValueTarget target = serviceProvider.GetService(typeof(IProvideValueTarget)) as IProvideValueTarget;
DependencyObject targetObject;
DependencyProperty targetProperty;
if (target != null && target.TargetObject is DependencyObject && target.TargetProperty is DependencyProperty)
{
targetObject = (DependencyObject)target.TargetObject;
targetProperty = (DependencyProperty)target.TargetProperty;
}
else
{
return this;
}
BindingOperations.SetBinding(targetObject, EnumToObjectArray.SourceEnumBindingSinkProperty, SourceEnum);
var type = targetObject.GetValue(SourceEnumBindingSinkProperty).GetType();
if (type.BaseType != typeof(System.Enum)) return this;
return Enum.GetValues(type)
.Cast<Enum>()
.Select(e => new { Value=e, Name = e.ToString(), DisplayName = Description(e) });
}
private static DependencyProperty SourceEnumBindingSinkProperty = DependencyProperty.RegisterAttached("SourceEnumBindingSink", typeof(Enum)
, typeof(EnumToObjectArray), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.Inherits));
/// <summary>
/// Extension method which returns the string specified in the Description attribute, if any. Oherwise, name is returned.
/// </summary>
/// <param name="value">The enum value.</param>
/// <returns></returns>
public static string Description(Enum value)
{
var attrs = value.GetType().GetField(value.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attrs.Any())
return (attrs.First() as DescriptionAttribute).Description;
//Fallback
return value.ToString().Replace("_", " ");
}
}
我添加了我的评论(遗憾的是在VB中,但是这个概念可以很容易地复制到c#中),因为我只是引用了这一点,并且不喜欢任何答案,因为它们太复杂了。没必要这么困难。
所以我想到了一个更简单的方法。将枚举数绑定到字典。将该字典绑定到组合框。
我的下拉列表框:
<ComboBox x:Name="cmbRole" VerticalAlignment="Stretch" IsEditable="False" Padding="2"
Margin="0" FontSize="11" HorizontalAlignment="Stretch" TabIndex="104"
SelectedValuePath="Key" DisplayMemberPath="Value" />
我的后台代码。希望这能帮助到其他人。
Dim tDict As New Dictionary(Of Integer, String)
Dim types = [Enum].GetValues(GetType(Helper.Enumerators.AllowedType))
For Each x As Helper.Enumerators.AllowedType In types
Dim z = x.ToString()
Dim y = CInt(x)
tDict.Add(y, z)
Next
cmbRole.ClearValue(ItemsControl.ItemsSourceProperty)
cmbRole.ItemsSource = tDict
使用ReactiveUI,我创建了以下替代解决方案。这不是一个优雅的一体化解决方案,但我认为至少它是可读的。
在我的例子中,将枚举列表绑定到控件是一种罕见的情况,所以我不需要跨代码库扩展解决方案。但是,可以通过更改EffectStyleLookup使代码更加通用。项目转化为对象。我用我的代码测试了,没有其他修改是必要的。这意味着一个helper类可以应用于任何枚举列表。虽然这会降低它的可读性- ReactiveList<EnumLookupHelper>并没有一个很好的环。
使用以下helper类:
public class EffectStyleLookup
{
public EffectStyle Item { get; set; }
public string Display { get; set; }
}
在ViewModel中,转换枚举列表并将其作为属性公开:
public ViewModel : ReactiveObject
{
private ReactiveList<EffectStyleLookup> _effectStyles;
public ReactiveList<EffectStyleLookup> EffectStyles
{
get { return _effectStyles; }
set { this.RaiseAndSetIfChanged(ref _effectStyles, value); }
}
// See below for more on this
private EffectStyle _selectedEffectStyle;
public EffectStyle SelectedEffectStyle
{
get { return _selectedEffectStyle; }
set { this.RaiseAndSetIfChanged(ref _selectedEffectStyle, value); }
}
public ViewModel()
{
// Convert a list of enums into a ReactiveList
var list = (IList<EffectStyle>)Enum.GetValues(typeof(EffectStyle))
.Select( x => new EffectStyleLookup() {
Item = x,
Display = x.ToString()
});
EffectStyles = new ReactiveList<EffectStyle>( list );
}
}
在组合框中,使用SelectedValuePath属性,绑定到原始enum值:
<ComboBox Name="EffectStyle" DisplayMemberPath="Display" SelectedValuePath="Item" />
在视图中,这允许我们将原始enum绑定到ViewModel中的SelectedEffectStyle,但在组合框中显示ToString()值:
this.WhenActivated( d =>
{
d( this.OneWayBind(ViewModel, vm => vm.EffectStyles, v => v.EffectStyle.ItemsSource) );
d( this.Bind(ViewModel, vm => vm.SelectedEffectStyle, v => v.EffectStyle.SelectedValue) );
});
简单明了的解释: http://brianlagunas.com/a-better-way-to-data-bind-enums-in-wpf/
xmlns:local="clr-namespace:BindingEnums"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
...
<Window.Resources>
<ObjectDataProvider x:Key="dataFromEnum" MethodName="GetValues"
ObjectType="{x:Type sys:Enum}">
<ObjectDataProvider.MethodParameters>
<x:Type TypeName="local:Status"/>
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
</Window.Resources>
...
<Grid>
<ComboBox HorizontalAlignment="Center" VerticalAlignment="Center" MinWidth="150"
ItemsSource="{Binding Source={StaticResource dataFromEnum}}"/>
</Grid>
这个问题有很多很好的答案,我谦卑地提出我的答案。我发现我的比较简单,也比较优雅。它只需要一个值转换器。
给定一个枚举…
public enum ImageFormat
{
[Description("Windows Bitmap")]
BMP,
[Description("Graphics Interchange Format")]
GIF,
[Description("Joint Photographic Experts Group Format")]
JPG,
[Description("Portable Network Graphics Format")]
PNG,
[Description("Tagged Image Format")]
TIFF,
[Description("Windows Media Photo Format")]
WDP
}
还有价值转换器……
public class ImageFormatValueConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is ImageFormat format)
{
return GetString(format);
}
return null;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is string s)
{
return Enum.Parse(typeof(ImageFormat), s.Substring(0, s.IndexOf(':')));
}
return null;
}
public string[] Strings => GetStrings();
public static string GetString(ImageFormat format)
{
return format.ToString() + ": " + GetDescription(format);
}
public static string GetDescription(ImageFormat format)
{
return format.GetType().GetMember(format.ToString())[0].GetCustomAttribute<DescriptionAttribute>().Description;
}
public static string[] GetStrings()
{
List<string> list = new List<string>();
foreach (ImageFormat format in Enum.GetValues(typeof(ImageFormat)))
{
list.Add(GetString(format));
}
return list.ToArray();
}
}
资源……
<local:ImageFormatValueConverter x:Key="ImageFormatValueConverter"/>
XAML份...
<ComboBox Grid.Row="9" ItemsSource="{Binding Source={StaticResource ImageFormatValueConverter}, Path=Strings}"
SelectedItem="{Binding Format, Converter={StaticResource ImageFormatValueConverter}}"/>
视图模型……
private ImageFormat _imageFormat = ImageFormat.JPG;
public ImageFormat Format
{
get => _imageFormat;
set
{
if (_imageFormat != value)
{
_imageFormat = value;
OnPropertyChanged();
}
}
}
产生的组合框……
Nick的解决方案可以更简化,没有什么花哨的,你只需要一个转换器:
[ValueConversion(typeof(Enum), typeof(IEnumerable<Enum>))]
public class EnumToCollectionConverter : MarkupExtension, IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var r = Enum.GetValues(value.GetType());
return r;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return null;
}
public override object ProvideValue(IServiceProvider serviceProvider)
{
return this;
}
}
然后在你想要组合框出现的地方使用这个:
<ComboBox ItemsSource="{Binding PagePosition, Converter={converter:EnumToCollectionConverter}, Mode=OneTime}" SelectedItem="{Binding PagePosition}" />
我不建议这样做,但希望这能启发一个好的解决方案。
假设枚举是Foo。然后你可以这样做。
public class FooViewModel : ViewModel
{
private int _fooValue;
public int FooValue
{
get => _fooValue;
set
{
_fooValue = value;
OnPropertyChange();
OnPropertyChange(nameof(Foo));
OnPropertyChange(nameof(FooName));
}
}
public Foo Foo
{
get => (Foo)FooValue;
set
{
_fooValue = (int)value;
OnPropertyChange();
OnPropertyChange(nameof(FooValue));
OnPropertyChange(nameof(FooName));
}
}
public string FooName { get => Enum.GetName(typeof(Foo), Foo); }
public FooViewModel(Foo foo)
{
Foo = foo;
}
}
然后打开Window。Load方法,你可以将所有枚举加载到ObservableCollection<FooViewModel>中,你可以将它设置为组合框的DataContext。
我只是保持简单。我在ViewModel中创建了一个枚举值的项目列表:
public enum InputsOutputsBoth
{
Inputs,
Outputs,
Both
}
private IList<InputsOutputsBoth> _ioTypes = new List<InputsOutputsBoth>()
{
InputsOutputsBoth.Both,
InputsOutputsBoth.Inputs,
InputsOutputsBoth.Outputs
};
public IEnumerable<InputsOutputsBoth> IoTypes
{
get { return _ioTypes; }
set { }
}
private InputsOutputsBoth _selectedIoType;
public InputsOutputsBoth SelectedIoType
{
get { return _selectedIoType; }
set
{
_selectedIoType = value;
OnPropertyChanged("SelectedIoType");
OnSelectionChanged();
}
}
在我的xaml代码中,我只需要这个:
<ComboBox ItemsSource="{Binding IoTypes}" SelectedItem="{Binding SelectedIoType, Mode=TwoWay}">
它的工作原理非常简单。 xaml
<ComboBox ItemsSource="{Binding MyEnumArray}">
.cs
public Array MyEnumArray
{
get { return Enum.GetValues(typeof(MyEnum)); }
}
<Window.Resources>
<ObjectDataProvider x:Key="DiaryTypeEnum"
MethodName="GetValues" ObjectType="{x:Type System:Enum}">
<ObjectDataProvider.MethodParameters>
<x:Type TypeName="z:Enums+DiaryType"/>
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
</Window.Resources>
...
<ComboBox ItemsSource="{Binding Source={StaticResource DiaryTypeEnum}}" SelectedItem="{x:Static z:Enums+DiaryType.Defect}" />
其中z它的xmlns:z="clr-namespace:ProjName。助手”
我的Enum变成静态类
public static class Enums
{
public enum DiaryType
{
State,
Defect,
Service,
Other
}
public enum OtherEnumOrMethods
{
//TODO
}
}
以下是我的简短回答。
public enum Direction { Left, Right, Up, Down };
public class Program
{
public Direction ScrollingDirection { get; set; }
public List<string> Directions { get; } = new List<string>();
public Program()
{
loadListDirection();
}
private void loadListDirection()
{
Directions.AddRange(Enum.GetNames(typeof(Direction)));
}
}
和Xaml:
<ComboBox SelectedIndex="0" ItemsSource="{Binding Path=Directions, Mode=OneWay}" SelectedItem="{Binding Path=ScrollingDirection, Mode=TwoWay}"/>
好运!