목록을 얻는 방법 WPF의 app.config에서 값 컬렉션?
다음 예제는 ItemsControl 을 코드에서 가져온 BackupDirectories 목록으로 채 웁니다 .
app.config 파일에서 동일한 정보를 얻을 수 있도록 어떻게 변경할 수 있습니까?
XAML :
<Window x:Class="TestReadMultipler2343.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Grid Margin="10">
<Grid.RowDefinitions>
<RowDefinition Height="30"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="120"/>
<ColumnDefinition Width="160"/>
</Grid.ColumnDefinitions>
<TextBlock
Grid.Row="0"
Grid.Column="0"
Text="Title:"/>
<TextBlock
Grid.Row="0"
Grid.Column="1"
Text="{Binding Title}"/>
<TextBlock
Grid.Row="1"
Grid.Column="0"
Text="Backup Directories:"/>
<ItemsControl
Grid.Row="1"
Grid.Column="1"
ItemsSource="{Binding BackupDirectories}"/>
</Grid>
</Window>
코드 숨김 :
using System.Collections.Generic;
using System.Windows;
using System.Configuration;
using System.ComponentModel;
namespace TestReadMultipler2343
{
public partial class Window1 : Window, INotifyPropertyChanged
{
#region ViewModelProperty: Title
private string _title;
public string Title
{
get
{
return _title;
}
set
{
_title = value;
OnPropertyChanged("Title");
}
}
#endregion
#region ViewModelProperty: BackupDirectories
private List<string> _backupDirectories = new List<string>();
public List<string> BackupDirectories
{
get
{
return _backupDirectories;
}
set
{
_backupDirectories = value;
OnPropertyChanged("BackupDirectories");
}
}
#endregion
public Window1()
{
InitializeComponent();
DataContext = this;
Title = ConfigurationManager.AppSettings.Get("title");
GetBackupDirectoriesInternal();
}
void GetBackupDirectoriesInternal()
{
BackupDirectories.Add(@"C:\test1");
BackupDirectories.Add(@"C:\test2");
BackupDirectories.Add(@"C:\test3");
BackupDirectories.Add(@"C:\test4");
}
void GetBackupDirectoriesFromConfig()
{
//BackupDirectories = ConfigurationManager.AppSettings.GetValues("backupDirectories");
}
#region INotifiedProperty Block
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion
}
}
app.config :
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="title" value="Backup Tool" />
<!--<add key="backupDirectories">
<add value="C:\test1"/>
<add value="C:\test2"/>
<add value="C:\test3"/>
<add value="C:\test4"/>
</add>-->
</appSettings>
</configuration>
app.config 파일에서 사용자 지정 구성 섹션을 만들 수 있습니다. 꽤있다 몇 가지 자습서 의 주위에 당신이 시작하는가. 궁극적으로 다음과 같은 것을 가질 수 있습니다.
<configSections>
<section name="backupDirectories" type="TestReadMultipler2343.BackupDirectoriesSection, TestReadMultipler2343" />
</configSections>
<backupDirectories>
<directory location="C:\test1" />
<directory location="C:\test2" />
<directory location="C:\test3" />
</backupDirectories>
Richard의 답변을 보완하기 위해 다음은 그의 샘플 구성과 함께 사용할 수있는 C #입니다.
using System.Collections.Generic;
using System.Configuration;
using System.Xml;
namespace TestReadMultipler2343
{
public class BackupDirectoriesSection : IConfigurationSectionHandler
{
public object Create(object parent, object configContext, XmlNode section)
{
List<directory> myConfigObject = new List<directory>();
foreach (XmlNode childNode in section.ChildNodes)
{
foreach (XmlAttribute attrib in childNode.Attributes)
{
myConfigObject.Add(new directory() { location = attrib.Value });
}
}
return myConfigObject;
}
}
public class directory
{
public string location { get; set; }
}
}
그런 다음 다음과 같이 backupDirectories 구성 섹션에 액세스 할 수 있습니다.
List<directory> dirs = ConfigurationManager.GetSection("backupDirectories") as List<directory>;
세미콜론을 단일 값으로 구분할 수 있습니다. 예 :
App.config
<add key="paths" value="C:\test1;C:\test2;C:\test3" />
씨#
var paths = new List<string>(ConfigurationManager.AppSettings["paths"].Split(new char[] { ';' }));
이 목적을 위해 BCL에는 실제로 알려진 클래스가 거의 없습니다 : CommaDelimitedStringCollectionConverter . 그것은 ConfigurationElementCollection
(Richard의 대답에서와 같이 ) a를 갖는 것과 (Adam의 대답에서와 같이) 문자열을 직접 구문 분석하는 것 사이의 중간 지점 역할을합니다 .
예를 들어 다음 구성 섹션을 작성할 수 있습니다.
public class MySection : ConfigurationSection
{
[ConfigurationProperty("MyStrings")]
[TypeConverter(typeof(CommaDelimitedStringCollectionConverter))]
public CommaDelimitedStringCollection MyStrings
{
get { return (CommaDelimitedStringCollection)base["MyStrings"]; }
}
}
그런 다음 다음과 같은 app.config를 가질 수 있습니다.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="foo" type="ConsoleApplication1.MySection, ConsoleApplication1"/>
</configSections>
<foo MyStrings="a,b,c,hello,world"/>
</configuration>
마지막으로 코드는 다음과 같습니다.
var section = (MySection)ConfigurationManager.GetSection("foo");
foreach (var s in section.MyStrings)
Console.WriteLine(s); //for example
나는 Richard Nienaber의 대답을 좋아하지만 Chuu가 지적했듯이 Richard가 해결책으로 언급 한 것을 달성하는 방법 을 실제로 알려주지 않습니다 . 그러므로 나는 내가이 일을하게 된 방식을 제공하기로 결정했고, Richard가 말한 결과로 끝났습니다.
해결책
이 경우 어떤 옵션이 인사해야하는지 알아야하는 인사 위젯을 만들고 있습니다. 가능한 미래 위젯을위한 컨테이너를 만들고 있기 때문에 이것은 OP 질문에 대한 과잉 엔지니어링 된 솔루션 일 수 있습니다.
먼저 다른 인사말을 처리하도록 컬렉션을 설정했습니다.
public class GreetingWidgetCollection : System.Configuration.ConfigurationElementCollection
{
public List<IGreeting> All { get { return this.Cast<IGreeting>().ToList(); } }
public GreetingElement this[int index]
{
get
{
return base.BaseGet(index) as GreetingElement;
}
set
{
if (base.BaseGet(index) != null)
{
base.BaseRemoveAt(index);
}
this.BaseAdd(index, value);
}
}
protected override ConfigurationElement CreateNewElement()
{
return new GreetingElement();
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((GreetingElement)element).Greeting;
}
}
그런 다음 acutal greeting 요소를 만들고 인터페이스입니다.
(인터페이스를 생략 할 수 있습니다. 이것이 제가 항상하는 방식입니다.)
public interface IGreeting
{
string Greeting { get; set; }
}
public class GreetingElement : System.Configuration.ConfigurationElement, IGreeting
{
[ConfigurationProperty("greeting", IsRequired = true)]
public string Greeting
{
get { return (string)this["greeting"]; }
set { this["greeting"] = value; }
}
}
구성이 컬렉션을 이해하도록하는 greetingWidget 속성
결과 XML에서 "greetingWidget"을 컨테이너로 사용할 수 있도록 컬렉션을 GreetingWidgetCollection
로 정의 ConfigurationProperty
greetingWidget
합니다.
public class Widgets : System.Configuration.ConfigurationSection
{
public static Widgets Widget => ConfigurationManager.GetSection("widgets") as Widgets;
[ConfigurationProperty("greetingWidget", IsRequired = true)]
public GreetingWidgetCollection GreetingWidget
{
get { return (GreetingWidgetCollection) this["greetingWidget"]; }
set { this["greetingWidget"] = value; }
}
}
결과 XML
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<widgets>
<greetingWidget>
<add greeting="Hej" />
<add greeting="Goddag" />
<add greeting="Hello" />
...
<add greeting="Konnichiwa" />
<add greeting="Namaskaar" />
</greetingWidget>
</widgets>
</configuration>
그리고 당신은 이것을 이렇게 부를 것입니다
List<GreetingElement> greetings = Widgets.GreetingWidget.All;
같은 문제가 있었지만 다른 방식으로 해결했습니다. 최선의 해결책이 아닐 수도 있지만 그 해결책입니다.
app.config에서 :
<add key="errorMailFirst" value="test@test.no"/>
<add key="errorMailSeond" value="krister@tets.no"/>
Then in my configuration wrapper class, I add a method to search keys.
public List<string> SearchKeys(string searchTerm)
{
var keys = ConfigurationManager.AppSettings.Keys;
return keys.Cast<object>()
.Where(key => key.ToString().ToLower()
.Contains(searchTerm.ToLower()))
.Select(key => ConfigurationManager.AppSettings.Get(key.ToString())).ToList();
}
For anyone reading this, i agree that creating your own custom configuration section is cleaner, and more secure, but for small projects, where you need something quick, this might solve it.
In App.config:
<add key="YOURKEY" value="a,b,c"/>
In C#:
string[] InFormOfStringArray = ConfigurationManager.AppSettings["YOURKEY"].Split(',').Select(s => s.Trim()).ToArray();
List<string> list = new List<string>(InFormOfStringArray);
Thank for the question. But I have found my own solution to this problem. At first, I created a method
public T GetSettingsWithDictionary<T>() where T:new()
{
IConfigurationRoot _configurationRoot = new ConfigurationBuilder()
.AddXmlFile($"{Assembly.GetExecutingAssembly().Location}.config", false, true).Build();
var instance = new T();
foreach (var property in typeof(T).GetProperties())
{
if (property.PropertyType == typeof(Dictionary<string, string>))
{
property.SetValue(instance, _configurationRoot.GetSection(typeof(T).Name).Get<Dictionary<string, string>>());
break;
}
}
return instance;
}
Then I used this method to produce an instance of a class
var connStrs = GetSettingsWithDictionary<AuthMongoConnectionStrings>();
I have the next declaration of class
public class AuthMongoConnectionStrings
{
public Dictionary<string, string> ConnectionStrings { get; set; }
}
and I store my setting in App.config
<configuration>
<AuthMongoConnectionStrings
First="first"
Second="second"
Third="33" />
</configuration>
'Programing' 카테고리의 다른 글
UIButton 제목 정렬 및 여러 줄 지원 (0) | 2020.11.06 |
---|---|
django / python에서 이메일의 유효성 확인 (0) | 2020.11.06 |
XOR 변수 스와핑은 어떻게 작동합니까? (0) | 2020.11.06 |
ClearCase 장점 / 단점 (0) | 2020.11.06 |
Android 활동이 대화 상자로 표시되지만 제목 표시 줄이 없음 (0) | 2020.11.06 |