DepartmentProject/DepartmentPortal/Common/DesktopTools/BaseControls/BaseControlImage.cs

101 lines
2.5 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
namespace DesktopTools.BaseControls
{
/// <summary>
/// Контрол, предоставляющий работу с изображением
/// </summary>
public partial class BaseControlImage : AbstractBaseControl
{
/// <summary>
/// Конструктор
/// </summary>
/// <param name="propertyName"></param>
/// <param name="mustFilling"></param>
/// <param name="readOnly"></param>
/// <param name="width"></param>
/// <param name="height"></param>
public BaseControlImage(string propertyName, bool mustFilling, bool readOnly, int? width, int? height) : base(propertyName, mustFilling, readOnly)
{
InitializeComponent();
if (width.HasValue)
{
Width = width.Value;
}
if (height.HasValue)
{
Height = height.Value;
}
buttonLoad.Click += (object sender, EventArgs e) =>
{
var dialog = new OpenFileDialog();
if (dialog.ShowDialog() == DialogResult.OK)
{
try
{
pictureBox.ClientSize = new Size(150, 150);
pictureBox.Image = new Bitmap(dialog.FileName);
CallOnValueChangeEvent();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при загрузке файла", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
};
panelControl.Controls.Add(pictureBox);
}
protected override void SetDefaultValue() => _originalValue = null;
protected override void SetValueToControl(object value)
{
if (value != null)
{
using MemoryStream mStream = new(value as byte[]);
pictureBox.Image = Image.FromStream(mStream);
}
else if (!_mustFilling)
{
pictureBox.Image = null;
}
}
public override void DropValue()
{
if (_originalValue != null)
{
using MemoryStream mStream = new(_originalValue as byte[]);
pictureBox.Image = Image.FromStream(mStream);
}
else if (!_mustFilling)
{
pictureBox.Image = null;
}
}
public override bool CheckValue()
{
if (_mustFilling && pictureBox.Image == null)
{
BackColor = Color.OrangeRed;
return false;
}
return true;
}
protected override object GetValueFromControl()
{
if (_mustFilling && pictureBox.Image == null)
{
throw new ArgumentNullException($"Поле свойства '{labelTitle.Text}' должно быть заполнено");
}
var converter = new ImageConverter();
return (byte[])converter.ConvertTo(pictureBox.Image, typeof(byte[]));
}
}
}