MvCamera.cs 26 KB

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