94 lines
3.2 KiB
C#
94 lines
3.2 KiB
C#
using System.Reflection;
|
||
|
||
namespace RodionovLibrary.VisualComponents
|
||
{
|
||
public partial class ListBoxControl : UserControl
|
||
{
|
||
private string? _template;
|
||
|
||
private char? _fromChar;
|
||
|
||
private char? _toChar;
|
||
|
||
public int SelectedIndex
|
||
{
|
||
get
|
||
{
|
||
return listBox.SelectedIndex;
|
||
}
|
||
set
|
||
{
|
||
listBox.SelectedIndex = value;
|
||
}
|
||
}
|
||
|
||
public ListBoxControl()
|
||
{
|
||
InitializeComponent();
|
||
}
|
||
|
||
public void SetParams(string template, char fromChar, char toChar)
|
||
{
|
||
_template = template;
|
||
_fromChar = fromChar;
|
||
_toChar = toChar;
|
||
}
|
||
|
||
public T? GetObject<T>()
|
||
{
|
||
if (listBox.SelectedIndex == -1 || string.IsNullOrEmpty(_template) || !_fromChar.HasValue || !_toChar.HasValue)
|
||
throw new ArgumentException("Не хватает данных");
|
||
|
||
var type = typeof(T);
|
||
var properties = type.GetProperties();
|
||
var curObject = Activator.CreateInstance(type);
|
||
|
||
string[] wordsTemplate = _template.Split(' ');
|
||
string[] words = listBox.SelectedItem.ToString().Split(' ');
|
||
|
||
for (int i = 0; i < wordsTemplate.Length; i++)
|
||
{
|
||
string word = wordsTemplate[i];
|
||
if (word.Contains(_fromChar.Value) && word.Contains(_toChar.Value))
|
||
{
|
||
int startCharIndex = word.IndexOf(_fromChar.Value);
|
||
int endCharIndex = word.LastIndexOf(_toChar.Value);
|
||
|
||
string propertyName = word.Substring(startCharIndex + 1, endCharIndex - startCharIndex - 1);
|
||
var property = properties.FirstOrDefault(x => x.Name == propertyName);
|
||
if (property == null)
|
||
continue;
|
||
|
||
int extraCharsBefore = startCharIndex;
|
||
int extraCharsAfter = word.Length - endCharIndex - 1;
|
||
|
||
string propertyValue = words[i].Substring(extraCharsBefore,
|
||
words[i].Length - extraCharsBefore - extraCharsAfter);
|
||
property.SetValue(curObject, Convert.ChangeType(propertyValue, property.PropertyType));
|
||
}
|
||
}
|
||
return (T?)curObject;
|
||
}
|
||
|
||
public void AddItems<T>(List<T> items)
|
||
where T : class
|
||
{
|
||
if (string.IsNullOrEmpty(_template) || !_fromChar.HasValue || !_toChar.HasValue)
|
||
throw new ArgumentException("Не хватает данных");
|
||
listBox.Items.Clear();
|
||
var type = typeof(T);
|
||
var properties = type.GetProperties();
|
||
foreach (T item in items)
|
||
{
|
||
string result = _template;
|
||
foreach (var property in properties)
|
||
{
|
||
string search = _fromChar.Value + property.Name + _toChar.Value;
|
||
result = result.Replace(search, property.GetValue(item)?.ToString() ?? "");
|
||
}
|
||
listBox.Items.Add(result);
|
||
}
|
||
}
|
||
}
|
||
}
|