Feedback

C# - Enumwerte als ItemsSource

Veröffentlicht von am 11/5/2015
(0 Bewertungen)
Mit diesem Attached Property kann man einfach die Itemssource zB. einer ListBox mit den Werten eins enums setzen. So müssen die einzelnen Werte nicht explizit angegeben werden und das Control ist auch resistent gegen Änderungen im betreffenden Enumtyp (zB. kann ein neuer Wert nicht "vergessen werden")
/// <summary>
/// Implements a setter for the <c>ItemsSource</c>-property 
/// Usage: <c><![CDATA[<ListBox enumSource:EnumSource.EnumType="my:EnumType"/>]]></c>
/// </summary>
public class EnumSource : DependencyObject
{
	public static readonly DependencyProperty EnumTypeProperty =
		DependencyProperty.RegisterAttached(
			"EnumType",
			typeof(Type),
			typeof(EnumSource),
			new UIPropertyMetadata(null, EnumTypeChanged));

	public static Type GetEnumType(DependencyObject obj) => (Type)obj.GetValue(EnumTypeProperty);

	public static void SetEnumType(DependencyObject obj, Type value) => obj.SetValue(EnumTypeProperty, value);

	private static void EnumTypeChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
	{
		var enumType = GetEnumType(sender);
		if (enumType != null && !enumType.IsEnum)
		{
			throw new ArgumentException($"{enumType} is not an enum type");
		}

		var itemsSource = sender.GetType().GetProperty("ItemsSource");
		if (itemsSource == null)
		{
			throw new InvalidOperationException($"{sender} has no ItemsSource property");
		}

		itemsSource.SetValue(
			sender,
			enumType == null ? null : Enum.GetValues(enumType),
			null);
	}
}

Abgelegt unter WPF, ItemsSource, enum.

1 Kommentare zum Snippet

Koopakiller schrieb am 11/5/2015:
Ich hätte mich eher für eine Markup Extension entschieden:
http://dotnet-snippets.de/snippet/wpf-markup-erweiterung-fuer-enumerationswerte/11027

Trotzdem gute Idee!
 

Logge dich ein, um hier zu kommentieren!