问题
I have an enum listing all possible settings:
public enum Settings
{
Settings1,
Settings2,
Settings3
}
In my user control i want to implement a new depedency property that holds a list of settings and be able to use it like this:
<my:Control Settings="Settings1, Settings2" />
How should i implement this?
回答1:
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();
}
}
回答2:
In your UserControl, make your Dependency property a collection of Settings
(perhaps 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 haven't tested this :)
If you want to stick with a comma separated list, then make your UserControl Settings DP a string, and then on the property changed event handler, split the string and use Enum.Parse
on each result to store the settings as your Setting
enum type.
来源:https://stackoverflow.com/questions/4714193/wpf-dependency-property-enum-collection