我似乎无法从 XAML 引用公共(public)嵌套枚举类型。我有课
namespace MyNamespace
{
public class MyClass
{
public enum MyEnum
{
A,
B,
}
}
}
我尝试像这样在 Xaml 中引用 MyEnum
:
xmlns:MyNamespace="clr-namespace:MyNamespace;assembly=MyApp"
....
{x:Type MyNamespace:MyClass:MyEnum} // DOESN'T WORK
但是 VS 提示它找不到公共(public)类型 MyEnum
。我还尝试根据 this post 的答案之一使用 +
语法...
{x:Type MyNamespace:MyClass+MyEnum} // DOESN'T WORK
但这也行不通。
请注意 x:Static
确实使用 +
语法:
{x:Static MyNamespace:MyClass+MyEnum.A} // WORKS
如果我将 MyEnum
移出 MyClass
,我也可以引用它。但如果它是嵌套的...
那我错过了什么?如何使用 x:Type
从 XAML 引用嵌套枚举? (请注意,我不是要实例化任何东西,只是引用类型)。
更新
看起来这只是 VS 2010 设计器的一个错误。设计者提示 Type MyNamespace:MyClass+MyEnum was not found
。但是应用程序似乎可以运行并正确访问嵌套类型。我也用嵌套类试过这个,它在运行时工作。
可能存在的错误:http://social.msdn.microsoft.com/forums/en-US/wpf/thread/12f3e120-e217-4eee-ab49-490b70031806/
最佳答案
这里有点晚了,但我使用了标记扩展,然后在我的 xaml 中使用了以下引用来引用组合框中的嵌套枚举:
xmlns:MyNamespace="clr-namespace:MyNamespace;assembly=MyApp"
...
ItemsSource="{Binding Source={resource:EnumBindingSource {x:Type MyNamespace:MyClass+MyEnum}}}"
MarkupExtension 的代码取自 here
public class EnumBindingSourceExtension : MarkupExtension
{
private Type _enumType;
public Type EnumType
{
get { return this._enumType; }
set
{
if (value != this._enumType)
{
if (null != value)
{
Type enumType = Nullable.GetUnderlyingType(value) ?? value;
if (!enumType.IsEnum)
throw new ArgumentException("Type must be for an Enum.");
}
this._enumType = value;
}
}
}
public EnumBindingSourceExtension() { }
public EnumBindingSourceExtension(Type enumType)
{
this.EnumType = enumType;
}
public override object ProvideValue(IServiceProvider serviceProvider)
{
if (null == this._enumType)
throw new InvalidOperationException("The EnumType must be specified.");
Type actualEnumType = Nullable.GetUnderlyingType(this._enumType) ?? this._enumType;
Array enumValues = Enum.GetValues(actualEnumType);
if (actualEnumType == this._enumType)
return enumValues;
Array tempArray = Array.CreateInstance(actualEnumType, enumValues.Length + 1);
enumValues.CopyTo(tempArray, 1);
return tempArray;
}
}
关于c# - 从 XAML 引用嵌套枚举类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13368099/