wpf dependency property enum collection

筅森魡賤 提交于 2020-01-11 07:22:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!