Как сохранить ItemsSource для ItemsControl (ListBox, ComboBox) в app.config? - PullRequest
0 голосов
/ 21 марта 2010

После долгих исследований, проб и ошибок я обнаружил, как хранить элементы для ListBox и ComboBox в app.Config. Я очень признателен Джону Ристе, который написал серию статей о классах конфигурации Net 2.0 . Я создал (большой!) Фрагмент кода, который сгенерирует весь необходимый код, просто вставив три строки!

Наслаждайтесь!

1 Ответ

0 голосов
/ 21 марта 2010
<?xml version="1.0" encoding="utf-8"?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <CodeSnippet Format="1.0.0">
    <Header>
      <Title>ConfigurationElementCollectionBasicMap</Title>
      <Author>Andre Steffens, heavily indebted to Jon Rista</Author>
      <Description>Derive from ConfigurationElementCollection of type BasicMap: Collection and Section</Description>
      <HelpUrl></HelpUrl>
      <SnippetTypes />
      <Keywords />
      <Shortcut>cecb</Shortcut>
    </Header>
    <Snippet>
      <References />
      <Imports />
      <Declarations>
        <Literal Editable="true">
          <ID>tag</ID>
          <Type></Type>
          <ToolTip></ToolTip>
          <Default>tag</Default>
          <Function></Function>
        </Literal>
        <Literal Editable="true">
          <ID>NameSpace</ID>
          <Type></Type>
          <ToolTip></ToolTip>
          <Default>NameSpace</Default>
          <Function></Function>
        </Literal>
        <Literal Editable="true">
          <ID>Type</ID>
          <Type></Type>
          <ToolTip></ToolTip>
          <Default>My</Default>
          <Function></Function>
        </Literal>
      </Declarations>
      <Code Language="csharp" Kind="type decl" Delimiter="$"><![CDATA[using System.Configuration;

namespace $NameSpace$.Configuration
{
    public class $Type$ElementCollection: ConfigurationElementCollection
    {
        #region Constructor
        public $Type$ElementCollection()
        {
        }
        #endregion

        #region Properties
        public override ConfigurationElementCollectionType CollectionType
        {
            get { return ConfigurationElementCollectionType.BasicMap; }
        }
        protected override string ElementName
        {
            get { return "$tag$"; }
        }

        protected override ConfigurationPropertyCollection Properties
        {
            get { return new ConfigurationPropertyCollection(); }
        }
        #endregion

        #region Indexers
        public $Type$Element this[int index]
        {
            get{ return ($Type$Element)BaseGet(index);}

            set
            {
                if (BaseGet(index) != null) BaseRemoveAt(index);
                base.BaseAdd(index, value);
            }
        }

        public new $Type$Element this[string key]
        {
            get { return ($Type$Element) BaseGet(key); }
        }
        #endregion

        #region Methods
        public void Add($Type$Element item)
        {
            base.BaseAdd(item);
        }

        public void Remove($Type$Element item)
        {
            BaseRemove(item);
        }

        public void RemoveAt(int index)
        {
            BaseRemoveAt(index);
        }
        #endregion

        #region Overrides
        protected override ConfigurationElement CreateNewElement()
        {
            return new $Type$Element();
        }

        protected override object GetElementKey(ConfigurationElement element)
        {
            var configurationElement = element as $Type$Element;
            return configurationElement == null
                       ? null
                       : configurationElement.Key;
        }
        #endregion
    }

    public class $Type$sSection: ConfigurationSection
    {
        #region Constructors
        static $Type$sSection()
        {
            s_name = new ConfigurationProperty(
                "name",
                typeof(string),
                null,
                ConfigurationPropertyOptions.IsRequired
                );

            s_$tag$s = new ConfigurationProperty(
                "",
                typeof($Type$ElementCollection),
                null,
                ConfigurationPropertyOptions.IsRequired | ConfigurationPropertyOptions.IsDefaultCollection
                );

            s_properties = new ConfigurationPropertyCollection {s_name, s_$tag$s};
        }
        #endregion

        #region Fields
        private static readonly ConfigurationPropertyCollection s_properties;
        private static readonly ConfigurationProperty s_name;
        private static readonly ConfigurationProperty s_$tag$s;
        #endregion

        #region Properties
        public string Name
        {
            get { return (string)base[s_name]; }
            set { base[s_name] = value; }
        }

        public $Type$ElementCollection $Type$s
        {
            get { return ($Type$ElementCollection)base[s_$tag$s]; }
        }

        protected override ConfigurationPropertyCollection Properties
        {
            get { return s_properties; }
        }
        #endregion
    }

    public class $Type$Element: ConfigurationElement
    {
        #region Constructors
        static $Type$Element()
        {
            s_key = new ConfigurationProperty(
                "key",
                typeof(string),
                null,
                ConfigurationPropertyOptions.IsRequired
                );

            s_value = new ConfigurationProperty(
                "value",
                typeof(string),
                null,
                ConfigurationPropertyOptions.None
                );

            //initialize further fields here

            s_properties = new ConfigurationPropertyCollection {s_key, s_value};
        }
        #endregion

        #region Fields
        private static readonly ConfigurationPropertyCollection s_properties;
        private static readonly ConfigurationProperty s_key;
        private static readonly ConfigurationProperty s_value;
        //add fields at your liberty!

        #endregion

        #region Properties
        public string Key
        {
            get { return (string)base[s_key]; }
            set { base[s_key] = value; }
        }

        public string Value
        {
            get { return (string)base[s_value]; }
            set { base[s_value] = value; }
        }

        //implement further properties here

        protected override ConfigurationPropertyCollection Properties
        {
            get { return s_properties; }
        }
    }
        #endregion
}

//example app.config snippet
/*
<configuration>
  <configSections>
    <section name="$tag$Listing" type="$NameSpace$.Configuration.$Type$sSection, $NameSpace$" />
  </configSections>

  <$tag$Listing name="$tag$s">
    <$tag$ key="key1" value="value1" />
    <$tag$ key="key2" value="value2" />
  </$tag$Listing>
</configuration>
*/]]></Code>
    </Snippet>
  </CodeSnippet>
</CodeSnippets>

Типичное использование будет:

//WPF
public Window1()
    {
        InitializeComponent();
        var section = ConfigurationManager.GetSection("$tag$Listing") as $Type$sSection;
        MyComboBox.ItemsSource = section.$Type$s;
        MyComboBox.DisplayMemberPath="Value";
    }

//WinForms
public Window1()
    {
        var section = ConfigurationManager.GetSection("$tag$Listing") as $Type$sSection;
        MyComboBox.Items = section.$Type$s;
        MyComboBox.DisplayMember="Value";
    }
...