Enum property of the wpf dependency property

I have an enumeration that lists all the possible settings:

public enum Settings { Settings1, Settings2, Settings3 } 

In my control, I want to implement a new depedency property that contains a list of settings and can use it as follows:

 <my:Control Settings="Settings1, Settings2" /> 

How do I implement this?

+1
source share
2 answers
 public class StringDelimitedToEnumListConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { List<Settings> retval = new List<Settings>(); if(value == null || value.GetType() != typeof(string) || targetType != typeof(List<Settings>) ) { throw new ArgumentException("value must be of type string, target type must be of type List<Settings>"); } string workingValue = value.ToString(); if (String.IsNullOrEmpty(workingValue)) { throw new ArgumentException("value must not be an empty string"); } if (workingValue.Contains(',')) { string[] tokens = workingValue.Split(','); foreach (string s in tokens) { retval.Add((Settings)Enum.Parse(typeof(Settings), s)); } return retval; } else { //there was only 1 value retval.Add((Settings)Enum.Parse(typeof(Settings),workingValue); return retval; } } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { //do we care? throw new NotImplementedException(); } } 
0
source

In your UserControl, make your Dependency resource a Settings collection (maybe rename your enum to Setting ) and then you can populate it in XAML with

 <my:Control> <my:Control.Settings> <x:Static Member="my:Setting.Setting1" /> <x:Static Member="my:Setting.Setting2" /> </my:Control.Settings> </my:Control> 

I have not tested this :)

If you want to stick to a comma-separated list, then make your UserControl DP settings a string, and then change the string in the property handler and use Enum.Parse for each result to save the settings as Setting enum type.

+3
source

Source: https://habr.com/ru/post/1391468/


All Articles