wpf依赖属性枚举集合

时间:2011-01-17 14:21:24

标签: wpf enums dependency-properties

我有一个列出所有可能设置的枚举:

public enum Settings
{
  Settings1,
  Settings2,
  Settings3
}

在我的用户控件中,我想实现一个新的依赖属性,它包含一个设置列表,并能够像这样使用它:

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

我该如何实现?

2 个答案:

答案 0 :(得分:3)

在UserControl中,将您的Dependency属性设为Settings的集合(可能将您的枚举重命名为Setting),然后您可以在XAML中填充它:

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

我没有测试过这个:)

如果您想坚持使用逗号分隔列表,然后将UserControl Settings DP设为字符串,然后在属性更改事件处理程序上,拆分字符串并在每个结果上使用Enum.Parse将设置存储为你的Setting枚举类型。

答案 1 :(得分:0)

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();
    }
}