In the namespace X
, I've got a public enum definition :
namespace X
{
public enum MyEnum
{ val0=0, val1, val2, val3, val4 }
}
In the namespace Y
I've got a class which has a property of the X.MyEnum
type
using namespace X;
namespace Y
{
class Container
{
public MyEnum MYEnum
{ get { return m_myenum; } set { m_myenum = value; } }
private MyEnum m_myenum;
}
}
I've created an user control which contains a ComboBox
. I'd very much like to databind it (TwoWay) to the MYEnum
field of the "Container". The usercontrol resides in the window.
How do I achieve that? I've seen开发者_开发百科 some examples with ObjectDataProvider
, however I'm lost.
You can define the ItemsSource
of the ComboBox
by using a custom markup extension that returns all values of the enum (this achieves the same result as using an ObjectDataProvider
, but it is simpler to use) :
[MarkupExtensionReturnType(typeof(Array))]
public class EnumValuesExtension : MarkupExtension
{
public EnumValuesExtension()
{
}
public EnumValuesExtension(Type enumType)
{
this.EnumType = enumType;
}
[ConstructorArgument("enumType")]
public Type EnumType { get; set; }
public override object ProvideValue(IServiceProvider serviceProvider)
{
return Enum.GetValues(EnumType);
}
}
And bind the SelectedItem to your MYEnum property :
<ComboBox ItemsSource="{local:EnumValues local:MyEnum}" SelectedItem="{Binding MYEnum, Mode=TwoWay}" />
(the local
XML namespace must be mapped to your C# namespace)
精彩评论