Сделал TemplatedListBox
This commit is contained in:
@@ -0,0 +1,12 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace WinFormsControlLibrary1.Exceptions;
|
||||
|
||||
public class TemplateConfigurationException : Exception
|
||||
{
|
||||
public TemplateConfigurationException(string message) : base(message) { }
|
||||
}
|
||||
37
WinFormsControlLibrary1/TemplatedListBox.Designer.cs
generated
Normal file
37
WinFormsControlLibrary1/TemplatedListBox.Designer.cs
generated
Normal file
@@ -0,0 +1,37 @@
|
||||
namespace WinFormsControlLibrary1
|
||||
{
|
||||
partial class TemplatedListBox
|
||||
{
|
||||
/// <summary>
|
||||
/// Обязательная переменная конструктора.
|
||||
/// </summary>
|
||||
private System.ComponentModel.IContainer components = null;
|
||||
|
||||
/// <summary>
|
||||
/// Освободить все используемые ресурсы.
|
||||
/// </summary>
|
||||
/// <param name="disposing">истинно, если управляемый ресурс должен быть удален; иначе ложно.</param>
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
if (disposing && (components != null))
|
||||
{
|
||||
components.Dispose();
|
||||
}
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
|
||||
#region Код, автоматически созданный конструктором компонентов
|
||||
|
||||
/// <summary>
|
||||
/// Требуемый метод для поддержки конструктора — не изменяйте
|
||||
/// содержимое этого метода с помощью редактора кода.
|
||||
/// </summary>
|
||||
private void InitializeComponent()
|
||||
{
|
||||
components = new System.ComponentModel.Container();
|
||||
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
141
WinFormsControlLibrary1/TemplatedListBox.cs
Normal file
141
WinFormsControlLibrary1/TemplatedListBox.cs
Normal file
@@ -0,0 +1,141 @@
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Data;
|
||||
using System.Drawing;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows.Forms;
|
||||
using WinFormsControlLibrary1.Exceptions;
|
||||
|
||||
namespace WinFormsControlLibrary1;
|
||||
|
||||
public partial class TemplatedListBox : UserControl
|
||||
{
|
||||
private readonly ListBox _lb = new();
|
||||
|
||||
private string _template = "";
|
||||
private char _open = '{';
|
||||
private char _close = '}';
|
||||
|
||||
private List<string> _placeholders = new();
|
||||
private readonly List<object> _items = new();
|
||||
|
||||
public event EventHandler? SelectedIndexChanged;
|
||||
public TemplatedListBox()
|
||||
{
|
||||
InitializeComponent();
|
||||
Controls.Add(_lb);
|
||||
_lb.SelectedIndexChanged += (_, __) => SelectedIndexChanged?.Invoke(this, EventArgs.Empty);
|
||||
}
|
||||
|
||||
public void SetTemplate(string template, char open = '{', char close = '}')
|
||||
{
|
||||
if(string.IsNullOrEmpty(template))
|
||||
throw new TemplateConfigurationException("Шаблон не должен быть пустым.");
|
||||
_template = template;
|
||||
_open = open;
|
||||
_close = close;
|
||||
_placeholders = ParsePlaceholders(template, open, close);
|
||||
|
||||
if (template[0] == open || template[template.Length - 1] == close)
|
||||
throw new TemplateConfigurationException("Шаблон не должен начинаться или заканчиваться свойством.");
|
||||
|
||||
CheckNoDoubleProperties(template,open, close);
|
||||
}
|
||||
|
||||
public void Clear()
|
||||
{
|
||||
_lb.Items.Clear();
|
||||
_items.Clear();
|
||||
}
|
||||
|
||||
public void AddItem<T>(T item)
|
||||
{
|
||||
if (string.IsNullOrEmpty(_template))
|
||||
throw new TemplateConfigurationException("Сначала вызовите SetTemplate.");
|
||||
var text = Render(item!);
|
||||
_lb.Items.Add(text);
|
||||
_items.Add(text);
|
||||
}
|
||||
|
||||
public T? GetSelected<T>()
|
||||
{
|
||||
int id = _lb.SelectedIndex;
|
||||
if (id < 0 || id >= _items.Count) return default;
|
||||
return _items[id] is T t ? t : default;
|
||||
}
|
||||
|
||||
private string Render(object obj)
|
||||
{
|
||||
var type = obj.GetType();
|
||||
var sb = new StringBuilder();
|
||||
int i = 0;
|
||||
while (i < _template.Length)
|
||||
{
|
||||
if (_template[i] == _open)
|
||||
{
|
||||
int j = _template.IndexOf(_close, i + 1);
|
||||
var name = _template.Substring(i + 1, j - i - 1);
|
||||
string val = GetMemberString(type, obj, name);
|
||||
sb.Append(val);
|
||||
i = j + 1;
|
||||
}
|
||||
else
|
||||
{
|
||||
sb.Append(_template[i]);
|
||||
i++;
|
||||
}
|
||||
}
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
private static string GetMemberString(Type t, object obj, string name)
|
||||
{
|
||||
var p = t.GetProperty(name);
|
||||
if (p != null) return Convert.ToString(p.GetValue(obj)) ?? string.Empty;
|
||||
|
||||
var f = t.GetField(name);
|
||||
if (f != null) return Convert.ToString(f.GetValue(obj)) ?? string.Empty;
|
||||
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
private static List<string> ParsePlaceholders(string template, char open, char close)
|
||||
{
|
||||
var list = new List<String>();
|
||||
int i = 0;
|
||||
while (i < template.Length)
|
||||
{
|
||||
if (template[i] == open)
|
||||
{
|
||||
int j = template.IndexOf(close, i + 1);
|
||||
if (j < 0) throw new TemplateConfigurationException("Несогласованные скобки в шаблоне.");
|
||||
string name = template.Substring(i + 1, j - i - 1).Trim();
|
||||
if (string.IsNullOrEmpty(name)) throw new TemplateConfigurationException("Пустое имя свойства в шаблоне.");
|
||||
list.Add(name);
|
||||
i = j + 1;
|
||||
}
|
||||
else i++;
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
private static void CheckNoDoubleProperties(string template, char open, char close)
|
||||
{
|
||||
for (int i = 0; i < template.Length; i++)
|
||||
{
|
||||
if (template[i] == close)
|
||||
{
|
||||
int k = i + 1;
|
||||
while (k < template.Length && char.IsWhiteSpace(template[k])) k++;
|
||||
if (k < template.Length && template[k] == open)
|
||||
throw new TemplateConfigurationException("В шаблоне не должно идти два свойства подряд без текста между ними.");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
120
WinFormsControlLibrary1/TemplatedListBox.resx
Normal file
120
WinFormsControlLibrary1/TemplatedListBox.resx
Normal file
@@ -0,0 +1,120 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<root>
|
||||
<!--
|
||||
Microsoft ResX Schema
|
||||
|
||||
Version 2.0
|
||||
|
||||
The primary goals of this format is to allow a simple XML format
|
||||
that is mostly human readable. The generation and parsing of the
|
||||
various data types are done through the TypeConverter classes
|
||||
associated with the data types.
|
||||
|
||||
Example:
|
||||
|
||||
... ado.net/XML headers & schema ...
|
||||
<resheader name="resmimetype">text/microsoft-resx</resheader>
|
||||
<resheader name="version">2.0</resheader>
|
||||
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
|
||||
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
|
||||
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
|
||||
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
|
||||
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
|
||||
<value>[base64 mime encoded serialized .NET Framework object]</value>
|
||||
</data>
|
||||
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
|
||||
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
|
||||
<comment>This is a comment</comment>
|
||||
</data>
|
||||
|
||||
There are any number of "resheader" rows that contain simple
|
||||
name/value pairs.
|
||||
|
||||
Each data row contains a name, and value. The row also contains a
|
||||
type or mimetype. Type corresponds to a .NET class that support
|
||||
text/value conversion through the TypeConverter architecture.
|
||||
Classes that don't support this are serialized and stored with the
|
||||
mimetype set.
|
||||
|
||||
The mimetype is used for serialized objects, and tells the
|
||||
ResXResourceReader how to depersist the object. This is currently not
|
||||
extensible. For a given mimetype the value must be set accordingly:
|
||||
|
||||
Note - application/x-microsoft.net.object.binary.base64 is the format
|
||||
that the ResXResourceWriter will generate, however the reader can
|
||||
read any of the formats listed below.
|
||||
|
||||
mimetype: application/x-microsoft.net.object.binary.base64
|
||||
value : The object must be serialized with
|
||||
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
|
||||
: and then encoded with base64 encoding.
|
||||
|
||||
mimetype: application/x-microsoft.net.object.soap.base64
|
||||
value : The object must be serialized with
|
||||
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
|
||||
: and then encoded with base64 encoding.
|
||||
|
||||
mimetype: application/x-microsoft.net.object.bytearray.base64
|
||||
value : The object must be serialized into a byte array
|
||||
: using a System.ComponentModel.TypeConverter
|
||||
: and then encoded with base64 encoding.
|
||||
-->
|
||||
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
|
||||
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
|
||||
<xsd:element name="root" msdata:IsDataSet="true">
|
||||
<xsd:complexType>
|
||||
<xsd:choice maxOccurs="unbounded">
|
||||
<xsd:element name="metadata">
|
||||
<xsd:complexType>
|
||||
<xsd:sequence>
|
||||
<xsd:element name="value" type="xsd:string" minOccurs="0" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="name" use="required" type="xsd:string" />
|
||||
<xsd:attribute name="type" type="xsd:string" />
|
||||
<xsd:attribute name="mimetype" type="xsd:string" />
|
||||
<xsd:attribute ref="xml:space" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name="assembly">
|
||||
<xsd:complexType>
|
||||
<xsd:attribute name="alias" type="xsd:string" />
|
||||
<xsd:attribute name="name" type="xsd:string" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name="data">
|
||||
<xsd:complexType>
|
||||
<xsd:sequence>
|
||||
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
|
||||
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
|
||||
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
|
||||
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
|
||||
<xsd:attribute ref="xml:space" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name="resheader">
|
||||
<xsd:complexType>
|
||||
<xsd:sequence>
|
||||
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="name" type="xsd:string" use="required" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
</xsd:choice>
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
</xsd:schema>
|
||||
<resheader name="resmimetype">
|
||||
<value>text/microsoft-resx</value>
|
||||
</resheader>
|
||||
<resheader name="version">
|
||||
<value>2.0</value>
|
||||
</resheader>
|
||||
<resheader name="reader">
|
||||
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
<resheader name="writer">
|
||||
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
</root>
|
||||
Reference in New Issue
Block a user