MvCamera.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700
  1. using Cognex.VisionPro;
  2. using CSScripting;
  3. using Microsoft.Win32;
  4. using MvCamCtrl.NET;
  5. using MvCamCtrl.NET.CameraParams;
  6. using NPOI.SS.Formula.Functions;
  7. using NPOI.Util;
  8. using NPOI.XSSF.Model;
  9. using OpenCvSharp.Dnn;
  10. using Org.BouncyCastle.Asn1.Tsp;
  11. using OxyPlot;
  12. using Sdcb.OpenVINO;
  13. using System;
  14. using System.Collections.Generic;
  15. using System.ComponentModel;
  16. using System.Diagnostics;
  17. using System.IO;
  18. using System.Linq;
  19. using System.Runtime.CompilerServices;
  20. using System.Runtime.InteropServices;
  21. using System.Text;
  22. using System.Threading;
  23. using System.Threading.Tasks;
  24. using System.Windows.Media.Media3D;
  25. using TeamAAS_VP;
  26. using TeamAAS_VP.Enums;
  27. using TeamAAS_VP.Interfaces;
  28. using TeamAAS_VP.Models;
  29. namespace TeamAAS_VP.Core.Cameras
  30. {
  31. public class MvCamera : ICamera, INotifyPropertyChanged
  32. {
  33. #region 字段
  34. private Thread m_hReceiveThread;
  35. // 用于序列化对同一相机实例的操作,防止同一实例被并发操作
  36. private readonly SemaphoreSlim _operationSemaphore = new SemaphoreSlim(1, 1);
  37. // 用于保护状态变量(例如 IsGrabbing)的并发访问
  38. private readonly object _stateLock = new object();
  39. #endregion
  40. #region 属性
  41. public CameraBrand CameraBrand { get => CameraBrand.HikRobot_MVS; }
  42. public string Name { get; private set; }
  43. public Guid ID { get; private set; }
  44. public int Index { get; set; }
  45. public string ManufacturerName { get; private set; }
  46. public bool IsFindByIp { get; private set; }
  47. public string ModelName { get; private set; }
  48. public string SerialNumber { get; private set; }
  49. public string CameraIp { get; private set; }
  50. public CameraType CameraType { get; private set; }
  51. MvCameraAcqTool.MvCameraAcqTool mvCameraAcq;
  52. public MyCamera.MV_CC_DEVICE_INFO CameraInfo { get; private set; }
  53. public UInt32 ImageWidth { get; private set; }
  54. public UInt32 ImageHeight { get; private set; }
  55. public MvGvspPixelType PixelType { get; private set; }
  56. private bool _IsGrabbing;
  57. /// <summary>
  58. /// 正在采集
  59. /// </summary>
  60. public bool IsGrabbing
  61. {
  62. get { return _IsGrabbing; }
  63. private set { SetProperty(ref _IsGrabbing, value); }
  64. }
  65. private ICogImage _Image;
  66. public ICogImage Image
  67. {
  68. get { return _Image; }
  69. private set { SetProperty(ref _Image, value); }
  70. }
  71. public bool IsConnected { get; private set; }
  72. private bool IsHaveCamera = false;
  73. /// <summary>
  74. /// 采集用时
  75. /// </summary>
  76. public TimeSpan TotalTime { get; private set; }
  77. /// <summary>
  78. /// 错误信息
  79. /// </summary>
  80. public string ErrorMessage { get; private set; }
  81. #endregion
  82. #region 事件
  83. public event Action<ICogImage, TimeSpan, string> ImageCallbackEvent;
  84. public event Action<Guid, bool> CameraConnectChangedEvent;
  85. #endregion
  86. public MvCamera(Guid id,int index, string name, string serialNumber,string cameraip,bool isFindByIp)
  87. {
  88. ID = id;
  89. Name = serialNumber;
  90. Index = index;
  91. CameraIp=cameraip;
  92. SerialNumber = serialNumber;
  93. IsFindByIp= isFindByIp;
  94. mvCameraAcq = new MvCameraAcqTool.MvCameraAcqTool();
  95. MyCamera.MV_CC_DEVICE_INFO_LIST stDeviceList = default(MyCamera.MV_CC_DEVICE_INFO_LIST);
  96. mvCameraAcq.EnumDeivce(ref stDeviceList);
  97. MyCamera.MV_CC_DEVICE_INFO device = default(MyCamera.MV_CC_DEVICE_INFO);
  98. for (int i = 0; i < stDeviceList.nDeviceNum; i++)
  99. {
  100. device = (MyCamera.MV_CC_DEVICE_INFO)Marshal.PtrToStructure(stDeviceList.pDeviceInfo[i], typeof(MyCamera.MV_CC_DEVICE_INFO));
  101. if (device.nTLayerType == CSystem.MV_GIGE_DEVICE)
  102. {
  103. MV_GIGE_DEVICE_INFO stGigEDeviceInfo = (MV_GIGE_DEVICE_INFO)MyCamera.ByteToStruct(device.SpecialInfo.stGigEInfo, typeof(MV_GIGE_DEVICE_INFO));
  104. uint nIp1 = ((stGigEDeviceInfo.nCurrentIp & 0xff000000) >> 24);
  105. uint nIp2 = ((stGigEDeviceInfo.nCurrentIp & 0x00ff0000) >> 16);
  106. uint nIp3 = ((stGigEDeviceInfo.nCurrentIp & 0x0000ff00) >> 8);
  107. uint nIp4 = (stGigEDeviceInfo.nCurrentIp & 0x000000ff);
  108. string ip= string.Format("{0}.{1}.{2}.{3}", nIp1, nIp2, nIp3, nIp4);
  109. if (IsFindByIp)
  110. {
  111. if (CameraIp == ip)
  112. {
  113. ManufacturerName = stGigEDeviceInfo.chManufacturerName;
  114. ModelName = stGigEDeviceInfo.chModelName;
  115. SerialNumber = stGigEDeviceInfo.chSerialNumber;
  116. CameraType = CameraType.GIGE;
  117. CameraInfo = device;
  118. IsHaveCamera = true;
  119. break;
  120. }
  121. }
  122. else
  123. {
  124. if (string.Equals(stGigEDeviceInfo.chSerialNumber, serialNumber))
  125. {
  126. ManufacturerName = stGigEDeviceInfo.chManufacturerName;
  127. ModelName = stGigEDeviceInfo.chModelName;
  128. SerialNumber = stGigEDeviceInfo.chSerialNumber;
  129. CameraType = CameraType.GIGE;
  130. CameraInfo = device;
  131. IsHaveCamera = true;
  132. break;
  133. }
  134. }
  135. }
  136. else if (device.nTLayerType == CSystem.MV_USB_DEVICE)
  137. {
  138. MV_USB3_DEVICE_INFO usbInfo = (MV_USB3_DEVICE_INFO)MyCamera.ByteToStruct(device.SpecialInfo.stUsb3VInfo, typeof(MV_USB3_DEVICE_INFO));
  139. if (string.Equals(usbInfo.chSerialNumber, serialNumber))
  140. {
  141. ManufacturerName = usbInfo.chManufacturerName;
  142. ModelName = usbInfo.chModelName;
  143. SerialNumber = usbInfo.chSerialNumber;
  144. CameraType = CameraType.USB;
  145. CameraInfo = device;
  146. IsHaveCamera = true;
  147. break;
  148. }
  149. }
  150. }
  151. IsConnected = false;
  152. }
  153. #region 方法
  154. /// <summary>
  155. /// 获取设备
  156. /// </summary>
  157. /// <returns></returns>
  158. public static CameraInfo[] GetDevices()
  159. {
  160. List<CameraInfo> cameras = new List<CameraInfo>();
  161. try
  162. {
  163. if (!CheckSoftwareInstalled().isInstalled)
  164. {
  165. LogHelper.WriteLogInfo("未安装MVS");
  166. return cameras.ToArray();
  167. }
  168. List<CCameraInfo> m_ltDeviceList = new List<CCameraInfo>();
  169. int nRet = CSystem.EnumDevices(CSystem.MV_GIGE_DEVICE | CSystem.MV_USB_DEVICE, ref m_ltDeviceList);
  170. if (0 != nRet)
  171. {
  172. return cameras.ToArray();
  173. }
  174. for (int i = 0; i < m_ltDeviceList.Count; i++)
  175. {
  176. if (m_ltDeviceList[i].nTLayerType == CSystem.MV_GIGE_DEVICE)
  177. {
  178. CGigECameraInfo gigeInfo = (CGigECameraInfo)m_ltDeviceList[i];
  179. uint nIp1 = ((gigeInfo.nCurrentIp & 0xff000000) >> 24);
  180. uint nIp2 = ((gigeInfo.nCurrentIp & 0x00ff0000) >> 16);
  181. uint nIp3 = ((gigeInfo.nCurrentIp & 0x0000ff00) >> 8);
  182. uint nIp4 = (gigeInfo.nCurrentIp & 0x000000ff);
  183. string ip = string.Format("{0}.{1}.{2}.{3}", nIp1, nIp2, nIp3, nIp4);
  184. cameras.Add(new CameraInfo()
  185. {
  186. CameraNo= i + 1,
  187. CameraName = gigeInfo.UserDefinedName,
  188. CameraBrand = CameraBrand.HikRobot_MVS,
  189. CameraType = CameraType.GIGE,
  190. ManufacturerName = gigeInfo.chManufacturerName,
  191. Model = gigeInfo.chModelName,
  192. SerialNumber = gigeInfo.chSerialNumber,
  193. CameraIp = ip,
  194. IsFindByIp=true,
  195. });
  196. }
  197. else if (m_ltDeviceList[i].nTLayerType == CSystem.MV_USB_DEVICE)
  198. {
  199. CUSBCameraInfo usbInfo = (CUSBCameraInfo)m_ltDeviceList[i];
  200. cameras.Add(new Models.CameraInfo()
  201. {
  202. CameraNo = i + 1,
  203. CameraName = usbInfo.UserDefinedName,
  204. CameraBrand = CameraBrand.HikRobot_MVS,
  205. CameraType = CameraType.USB,
  206. ManufacturerName = usbInfo.chManufacturerName,
  207. Model = usbInfo.chModelName,
  208. SerialNumber = usbInfo.chSerialNumber,
  209. CameraIp = "",
  210. });
  211. }
  212. else if (m_ltDeviceList[i].nTLayerType == CSystem.MV_CAMERALINK_DEVICE)
  213. {
  214. CCamLCameraInfo Info = (CCamLCameraInfo)m_ltDeviceList[i];
  215. cameras.Add(new Models.CameraInfo()
  216. {
  217. CameraNo = i + 1,
  218. CameraName = Info.chModelName,
  219. CameraBrand = CameraBrand.HikRobot_MVS,
  220. CameraType = CameraType.USB,
  221. ManufacturerName = Info.chManufacturerName,
  222. Model = Info.chModelName,
  223. SerialNumber = Info.chSerialNumber,
  224. CameraIp = "",
  225. });
  226. }
  227. }
  228. }
  229. catch (Exception ex)
  230. {
  231. LogHelper.WriteLogError("搜索海康相机列表时出错!", ex);
  232. }
  233. return cameras.ToArray();
  234. }
  235. /// <summary>
  236. /// 检查相机软件是否安装
  237. /// </summary>
  238. /// <returns></returns>
  239. public static (bool isInstalled, string version) CheckSoftwareInstalled()
  240. {
  241. string softwareName = "MVS";
  242. string softwareVersion = "4.4.0";
  243. string[] registryPaths = new[]
  244. {
  245. @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall",
  246. @"SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall"
  247. };
  248. foreach (var path in registryPaths)
  249. {
  250. using (RegistryKey key = Registry.LocalMachine.OpenSubKey(path))
  251. {
  252. if (key == null) continue;
  253. foreach (string subKeyName in key.GetSubKeyNames())
  254. {
  255. using (RegistryKey subKey = key.OpenSubKey(subKeyName))
  256. {
  257. string displayName = subKey.GetValue("DisplayName")?.ToString();
  258. if (displayName != null && displayName.ToUpper().Trim()==softwareName.ToUpper())
  259. {
  260. string version = subKey.GetValue("DisplayVersion")?.ToString();
  261. Version v1 = new Version(version);
  262. Version v2 = new Version(softwareVersion);
  263. if (v1 >= v2)
  264. {
  265. return (true, version);
  266. }
  267. else
  268. {
  269. return (false, version);
  270. }
  271. }
  272. }
  273. }
  274. }
  275. }
  276. return (false, "");
  277. }
  278. /// <summary>
  279. /// 打开相机
  280. /// </summary>
  281. /// <returns></returns>
  282. /// <exception cref="Exception"></exception>
  283. public bool OpenDevice()
  284. {
  285. _operationSemaphore.Wait();
  286. try
  287. {
  288. if (!IsHaveCamera)
  289. {
  290. mvCameraAcq = new MvCameraAcqTool.MvCameraAcqTool();
  291. MyCamera.MV_CC_DEVICE_INFO_LIST stDeviceList = default(MyCamera.MV_CC_DEVICE_INFO_LIST);
  292. mvCameraAcq.EnumDeivce(ref stDeviceList);
  293. MyCamera.MV_CC_DEVICE_INFO device = default(MyCamera.MV_CC_DEVICE_INFO);
  294. for (int i = 0; i < stDeviceList.nDeviceNum; i++)
  295. {
  296. device = (MyCamera.MV_CC_DEVICE_INFO)Marshal.PtrToStructure(stDeviceList.pDeviceInfo[i], typeof(MyCamera.MV_CC_DEVICE_INFO));
  297. if (device.nTLayerType == CSystem.MV_GIGE_DEVICE)
  298. {
  299. MV_GIGE_DEVICE_INFO stGigEDeviceInfo = (MV_GIGE_DEVICE_INFO)MyCamera.ByteToStruct(device.SpecialInfo.stGigEInfo, typeof(MV_GIGE_DEVICE_INFO));
  300. uint nIp1 = ((stGigEDeviceInfo.nCurrentIp & 0xff000000) >> 24);
  301. uint nIp2 = ((stGigEDeviceInfo.nCurrentIp & 0x00ff0000) >> 16);
  302. uint nIp3 = ((stGigEDeviceInfo.nCurrentIp & 0x0000ff00) >> 8);
  303. uint nIp4 = (stGigEDeviceInfo.nCurrentIp & 0x000000ff);
  304. string ip = string.Format("{0}.{1}.{2}.{3}", nIp1, nIp2, nIp3, nIp4);
  305. if (IsFindByIp)
  306. {
  307. if (CameraIp == ip)
  308. {
  309. ManufacturerName = stGigEDeviceInfo.chManufacturerName;
  310. ModelName = stGigEDeviceInfo.chModelName;
  311. SerialNumber = stGigEDeviceInfo.chSerialNumber;
  312. CameraType = CameraType.GIGE;
  313. CameraInfo = device;
  314. IsHaveCamera = true;
  315. break;
  316. }
  317. }
  318. else
  319. {
  320. if (string.Equals(stGigEDeviceInfo.chSerialNumber, SerialNumber))
  321. {
  322. ManufacturerName = stGigEDeviceInfo.chManufacturerName;
  323. ModelName = stGigEDeviceInfo.chModelName;
  324. SerialNumber = stGigEDeviceInfo.chSerialNumber;
  325. CameraType = CameraType.GIGE;
  326. CameraInfo = device;
  327. IsHaveCamera = true;
  328. break;
  329. }
  330. }
  331. }
  332. else if (device.nTLayerType == CSystem.MV_USB_DEVICE)
  333. {
  334. MV_USB3_DEVICE_INFO usbInfo = (MV_USB3_DEVICE_INFO)MyCamera.ByteToStruct(device.SpecialInfo.stUsb3VInfo, typeof(MV_USB3_DEVICE_INFO));
  335. if (string.Equals(usbInfo.chSerialNumber, SerialNumber))
  336. {
  337. ManufacturerName = usbInfo.chManufacturerName;
  338. ModelName = usbInfo.chModelName;
  339. SerialNumber = usbInfo.chSerialNumber;
  340. CameraType = CameraType.USB;
  341. CameraInfo = device;
  342. IsHaveCamera = true;
  343. break;
  344. }
  345. }
  346. }
  347. if (!IsHaveCamera)
  348. {
  349. throw new Exception("没有发现相机");
  350. }
  351. }
  352. mvCameraAcq.OpenDevice(CameraInfo);
  353. mvCameraAcq.AutoExposure = false;
  354. mvCameraAcq.TriggerMode = false;
  355. if (!IsConnected)
  356. {
  357. CameraConnectChangedEvent?.Invoke(ID, true);
  358. }
  359. IsConnected = mvCameraAcq.bIsOpened;
  360. return IsConnected;
  361. }
  362. finally
  363. {
  364. _operationSemaphore.Release();
  365. }
  366. }
  367. /// <summary>
  368. /// 打开相机异步
  369. /// </summary>
  370. /// <returns></returns>
  371. public Task<bool> OpenDeviceAsync()
  372. {
  373. return Task.Run(() =>
  374. {
  375. return OpenDevice();
  376. });
  377. }
  378. /// <summary>
  379. /// 关闭相机
  380. /// </summary>
  381. public void CloseDevice()
  382. {
  383. // ch:关闭设备 | en:Close Device
  384. _operationSemaphore.Wait();
  385. try
  386. {
  387. mvCameraAcq.CloseDevice();
  388. }
  389. finally
  390. {
  391. _operationSemaphore.Release();
  392. }
  393. }
  394. /// <summary>
  395. /// 采集图像
  396. /// </summary>
  397. /// <returns></returns>
  398. public ICogImage Grab()
  399. {
  400. _operationSemaphore.Wait();
  401. try
  402. {
  403. Stopwatch sw = Stopwatch.StartNew();
  404. for (int i = 0; i < 5; i++)
  405. {
  406. try
  407. {
  408. if (!mvCameraAcq.bIsOpened)
  409. {
  410. OpenDevice();
  411. }
  412. mvCameraAcq.Run();
  413. if (mvCameraAcq.RunStatus.Result == CogToolResultConstants.Accept)
  414. {
  415. ErrorMessage = "";
  416. Image = mvCameraAcq.OutputImage;
  417. if (!IsConnected)
  418. {
  419. IsConnected = true;
  420. CameraConnectChangedEvent?.Invoke(ID, true);
  421. }
  422. TotalTime = sw.Elapsed;
  423. return Image;
  424. }
  425. else
  426. {
  427. ErrorMessage = mvCameraAcq.RunStatus.Message;
  428. CloseDevice();
  429. OpenDevice();
  430. }
  431. }
  432. catch (Exception ex)
  433. {
  434. CloseDevice();
  435. OpenDevice();
  436. ErrorMessage = ex.Message;
  437. }
  438. }
  439. if (IsConnected)
  440. {
  441. IsConnected = false;
  442. CameraConnectChangedEvent?.Invoke(ID, false);
  443. }
  444. return null;
  445. }
  446. finally
  447. {
  448. _operationSemaphore.Release();
  449. }
  450. }
  451. /// <summary>
  452. /// 开始采集图像
  453. /// </summary>
  454. public void StartGrabbing()
  455. {
  456. lock (_stateLock)
  457. {
  458. if (IsGrabbing)
  459. return;
  460. IsGrabbing = true;
  461. }
  462. m_hReceiveThread = new Thread(GetStreamThreadProc) { IsBackground = true };
  463. m_hReceiveThread.Start();
  464. }
  465. /// <summary>
  466. /// 停止采集图像
  467. /// </summary>
  468. public void StopGrabbing()
  469. {
  470. try
  471. {
  472. lock (_stateLock)
  473. {
  474. IsGrabbing = false;
  475. }
  476. Thread.Sleep(1000);
  477. if (m_hReceiveThread != null)
  478. {
  479. m_hReceiveThread.Abort();
  480. m_hReceiveThread = null;
  481. }
  482. }
  483. catch (Exception)
  484. {
  485. }
  486. }
  487. /// <summary>
  488. /// 设置曝光时间
  489. /// </summary>
  490. /// <param name="ExposureTime"></param>
  491. /// <returns></returns>
  492. public bool SetExposureTime(float ExposureTime)
  493. {
  494. _operationSemaphore.Wait();
  495. try
  496. {
  497. if (!mvCameraAcq.bIsOpened)
  498. return false;
  499. mvCameraAcq.ExposureTime = (double)ExposureTime;
  500. return true;
  501. }
  502. finally
  503. {
  504. _operationSemaphore.Release();
  505. }
  506. }
  507. /// <summary>
  508. /// 获取曝光时间
  509. /// </summary>
  510. /// <returns></returns>
  511. public float GetExposureTime()
  512. {
  513. _operationSemaphore.Wait();
  514. try
  515. {
  516. if (!mvCameraAcq.bIsOpened)
  517. return 0;
  518. return (float)mvCameraAcq.ExposureTime;
  519. }
  520. finally
  521. {
  522. _operationSemaphore.Release();
  523. }
  524. }
  525. /// <summary>
  526. /// 设置增益
  527. /// </summary>
  528. /// <param name="Gain"></param>
  529. /// <returns></returns>
  530. public bool SetGain(float Gain)
  531. {
  532. _operationSemaphore.Wait();
  533. try
  534. {
  535. if (!mvCameraAcq.bIsOpened)
  536. return false;
  537. mvCameraAcq.AnalogGain = (double)Gain;
  538. return true;
  539. }
  540. finally
  541. {
  542. _operationSemaphore.Release();
  543. }
  544. }
  545. /// <summary>
  546. /// 获取增益
  547. /// </summary>
  548. /// <returns></returns>
  549. public float GetGain()
  550. {
  551. _operationSemaphore.Wait();
  552. try
  553. {
  554. if (!mvCameraAcq.bIsOpened)
  555. return 0;
  556. return (float)mvCameraAcq.AnalogGain;
  557. }
  558. finally
  559. {
  560. _operationSemaphore.Release();
  561. }
  562. }
  563. private void GetStreamThreadProc()
  564. {
  565. while (IsGrabbing)
  566. {
  567. try
  568. {
  569. Grab();
  570. ImageCallbackEvent?.Invoke(Image, TotalTime, ErrorMessage);
  571. }
  572. catch (Exception)
  573. {
  574. }
  575. Thread.Sleep(10);
  576. }
  577. IsGrabbing = false;
  578. }
  579. #endregion
  580. #region 属性通知
  581. /// <summary>
  582. /// Occurs when a property value changes.
  583. /// </summary>
  584. public event PropertyChangedEventHandler PropertyChanged;
  585. /// <summary>
  586. /// Checks if a property already matches a desired value. Sets the property and
  587. /// notifies listeners only when necessary.
  588. /// </summary>
  589. /// <typeparam name="T">Type of the property.</typeparam>
  590. /// <param name="storage">Reference to a property with both getter and setter.</param>
  591. /// <param name="value">Desired value for the property.</param>
  592. /// <param name="propertyName">Name of the property used to notify listeners. This
  593. /// value is optional and can be provided automatically when invoked from compilers that
  594. /// support CallerMemberName.</param>
  595. /// <returns>True if the value was changed, false if the existing value matched the
  596. /// desired value.</returns>
  597. protected virtual bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null)
  598. {
  599. if (EqualityComparer<T>.Default.Equals(storage, value)) return false;
  600. storage = value;
  601. RaisePropertyChanged(propertyName);
  602. return true;
  603. }
  604. /// <summary>
  605. /// Checks if a property already matches a desired value. Sets the property and
  606. /// notifies listeners only when necessary.
  607. /// </summary>
  608. /// <typeparam name="T">Type of the property.</typeparam>
  609. /// <param name="storage">Reference to a property with both getter and setter.</param>
  610. /// <param name="value">Desired value for the property.</param>
  611. /// <param name="propertyName">Name of the property used to notify listeners. This
  612. /// value is optional and can be provided automatically when invoked from compilers that
  613. /// support CallerMemberName.</param>
  614. /// <param name="onChanged">Action that is called after the property value has been changed.</param>
  615. /// <returns>True if the value was changed, false if the existing value matched the
  616. /// desired value.</returns>
  617. protected virtual bool SetProperty<T>(ref T storage, T value, Action onChanged, [CallerMemberName] string propertyName = null)
  618. {
  619. if (EqualityComparer<T>.Default.Equals(storage, value)) return false;
  620. storage = value;
  621. onChanged?.Invoke();
  622. RaisePropertyChanged(propertyName);
  623. return true;
  624. }
  625. /// <summary>
  626. /// Raises this object's PropertyChanged event.
  627. /// </summary>
  628. /// <param name="propertyName">Name of the property used to notify listeners. This
  629. /// value is optional and can be provided automatically when invoked from compilers
  630. /// that support <see cref="CallerMemberNameAttribute"/>.</param>
  631. protected void RaisePropertyChanged([CallerMemberName] string propertyName = null)
  632. {
  633. OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
  634. }
  635. /// <summary>
  636. /// Raises this object's PropertyChanged event.
  637. /// </summary>
  638. /// <param name="args">The PropertyChangedEventArgs</param>
  639. protected virtual void OnPropertyChanged(PropertyChangedEventArgs args)
  640. {
  641. PropertyChanged?.Invoke(this, args);
  642. }
  643. #endregion
  644. }
  645. }