MvCamera.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701
  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. /// <param name="lastImageOnly">true:采集一张新图像,false:返回最后一张图像</param>
  398. /// <returns></returns>
  399. public ICogImage Grab(bool lastImageOnly = true)
  400. {
  401. _operationSemaphore.Wait();
  402. try
  403. {
  404. Stopwatch sw = Stopwatch.StartNew();
  405. for (int i = 0; i < 5; i++)
  406. {
  407. try
  408. {
  409. if (!mvCameraAcq.bIsOpened)
  410. {
  411. OpenDevice();
  412. }
  413. mvCameraAcq.Run();
  414. if (mvCameraAcq.RunStatus.Result == CogToolResultConstants.Accept)
  415. {
  416. ErrorMessage = "";
  417. Image = mvCameraAcq.OutputImage;
  418. if (!IsConnected)
  419. {
  420. IsConnected = true;
  421. CameraConnectChangedEvent?.Invoke(ID, true);
  422. }
  423. TotalTime = sw.Elapsed;
  424. return Image;
  425. }
  426. else
  427. {
  428. ErrorMessage = mvCameraAcq.RunStatus.Message;
  429. CloseDevice();
  430. OpenDevice();
  431. }
  432. }
  433. catch (Exception ex)
  434. {
  435. CloseDevice();
  436. OpenDevice();
  437. ErrorMessage = ex.Message;
  438. }
  439. }
  440. if (IsConnected)
  441. {
  442. IsConnected = false;
  443. CameraConnectChangedEvent?.Invoke(ID, false);
  444. }
  445. return null;
  446. }
  447. finally
  448. {
  449. _operationSemaphore.Release();
  450. }
  451. }
  452. /// <summary>
  453. /// 开始采集图像
  454. /// </summary>
  455. public void StartGrabbing()
  456. {
  457. lock (_stateLock)
  458. {
  459. if (IsGrabbing)
  460. return;
  461. IsGrabbing = true;
  462. }
  463. m_hReceiveThread = new Thread(GetStreamThreadProc) { IsBackground = true };
  464. m_hReceiveThread.Start();
  465. }
  466. /// <summary>
  467. /// 停止采集图像
  468. /// </summary>
  469. public void StopGrabbing()
  470. {
  471. try
  472. {
  473. lock (_stateLock)
  474. {
  475. IsGrabbing = false;
  476. }
  477. Thread.Sleep(1000);
  478. if (m_hReceiveThread != null)
  479. {
  480. m_hReceiveThread.Abort();
  481. m_hReceiveThread = null;
  482. }
  483. }
  484. catch (Exception)
  485. {
  486. }
  487. }
  488. /// <summary>
  489. /// 设置曝光时间
  490. /// </summary>
  491. /// <param name="ExposureTime"></param>
  492. /// <returns></returns>
  493. public bool SetExposureTime(float ExposureTime)
  494. {
  495. _operationSemaphore.Wait();
  496. try
  497. {
  498. if (!mvCameraAcq.bIsOpened)
  499. return false;
  500. mvCameraAcq.ExposureTime = (double)ExposureTime;
  501. return true;
  502. }
  503. finally
  504. {
  505. _operationSemaphore.Release();
  506. }
  507. }
  508. /// <summary>
  509. /// 获取曝光时间
  510. /// </summary>
  511. /// <returns></returns>
  512. public float GetExposureTime()
  513. {
  514. _operationSemaphore.Wait();
  515. try
  516. {
  517. if (!mvCameraAcq.bIsOpened)
  518. return 0;
  519. return (float)mvCameraAcq.ExposureTime;
  520. }
  521. finally
  522. {
  523. _operationSemaphore.Release();
  524. }
  525. }
  526. /// <summary>
  527. /// 设置增益
  528. /// </summary>
  529. /// <param name="Gain"></param>
  530. /// <returns></returns>
  531. public bool SetGain(float Gain)
  532. {
  533. _operationSemaphore.Wait();
  534. try
  535. {
  536. if (!mvCameraAcq.bIsOpened)
  537. return false;
  538. mvCameraAcq.AnalogGain = (double)Gain;
  539. return true;
  540. }
  541. finally
  542. {
  543. _operationSemaphore.Release();
  544. }
  545. }
  546. /// <summary>
  547. /// 获取增益
  548. /// </summary>
  549. /// <returns></returns>
  550. public float GetGain()
  551. {
  552. _operationSemaphore.Wait();
  553. try
  554. {
  555. if (!mvCameraAcq.bIsOpened)
  556. return 0;
  557. return (float)mvCameraAcq.AnalogGain;
  558. }
  559. finally
  560. {
  561. _operationSemaphore.Release();
  562. }
  563. }
  564. private void GetStreamThreadProc()
  565. {
  566. while (IsGrabbing)
  567. {
  568. try
  569. {
  570. Grab();
  571. ImageCallbackEvent?.Invoke(Image, TotalTime, ErrorMessage);
  572. }
  573. catch (Exception)
  574. {
  575. }
  576. Thread.Sleep(10);
  577. }
  578. IsGrabbing = false;
  579. }
  580. #endregion
  581. #region 属性通知
  582. /// <summary>
  583. /// Occurs when a property value changes.
  584. /// </summary>
  585. public event PropertyChangedEventHandler PropertyChanged;
  586. /// <summary>
  587. /// Checks if a property already matches a desired value. Sets the property and
  588. /// notifies listeners only when necessary.
  589. /// </summary>
  590. /// <typeparam name="T">Type of the property.</typeparam>
  591. /// <param name="storage">Reference to a property with both getter and setter.</param>
  592. /// <param name="value">Desired value for the property.</param>
  593. /// <param name="propertyName">Name of the property used to notify listeners. This
  594. /// value is optional and can be provided automatically when invoked from compilers that
  595. /// support CallerMemberName.</param>
  596. /// <returns>True if the value was changed, false if the existing value matched the
  597. /// desired value.</returns>
  598. protected virtual bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null)
  599. {
  600. if (EqualityComparer<T>.Default.Equals(storage, value)) return false;
  601. storage = value;
  602. RaisePropertyChanged(propertyName);
  603. return true;
  604. }
  605. /// <summary>
  606. /// Checks if a property already matches a desired value. Sets the property and
  607. /// notifies listeners only when necessary.
  608. /// </summary>
  609. /// <typeparam name="T">Type of the property.</typeparam>
  610. /// <param name="storage">Reference to a property with both getter and setter.</param>
  611. /// <param name="value">Desired value for the property.</param>
  612. /// <param name="propertyName">Name of the property used to notify listeners. This
  613. /// value is optional and can be provided automatically when invoked from compilers that
  614. /// support CallerMemberName.</param>
  615. /// <param name="onChanged">Action that is called after the property value has been changed.</param>
  616. /// <returns>True if the value was changed, false if the existing value matched the
  617. /// desired value.</returns>
  618. protected virtual bool SetProperty<T>(ref T storage, T value, Action onChanged, [CallerMemberName] string propertyName = null)
  619. {
  620. if (EqualityComparer<T>.Default.Equals(storage, value)) return false;
  621. storage = value;
  622. onChanged?.Invoke();
  623. RaisePropertyChanged(propertyName);
  624. return true;
  625. }
  626. /// <summary>
  627. /// Raises this object's PropertyChanged event.
  628. /// </summary>
  629. /// <param name="propertyName">Name of the property used to notify listeners. This
  630. /// value is optional and can be provided automatically when invoked from compilers
  631. /// that support <see cref="CallerMemberNameAttribute"/>.</param>
  632. protected void RaisePropertyChanged([CallerMemberName] string propertyName = null)
  633. {
  634. OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
  635. }
  636. /// <summary>
  637. /// Raises this object's PropertyChanged event.
  638. /// </summary>
  639. /// <param name="args">The PropertyChangedEventArgs</param>
  640. protected virtual void OnPropertyChanged(PropertyChangedEventArgs args)
  641. {
  642. PropertyChanged?.Invoke(this, args);
  643. }
  644. #endregion
  645. }
  646. }