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. using TeamAAS_VP.Resources.Languages;
  30. namespace TeamAAS_VP.Core.Cameras
  31. {
  32. public class MvCamera : ICamera, INotifyPropertyChanged
  33. {
  34. #region 字段
  35. private Thread m_hReceiveThread;
  36. // 用于序列化对同一相机实例的操作,防止同一实例被并发操作
  37. private readonly SemaphoreSlim _operationSemaphore = new SemaphoreSlim(1, 1);
  38. // 用于保护状态变量(例如 IsGrabbing)的并发访问
  39. private readonly object _stateLock = new object();
  40. #endregion
  41. #region 属性
  42. public CameraBrand CameraBrand { get => CameraBrand.HikRobot_MVS; }
  43. public string Name { get; private set; }
  44. public Guid ID { get; private set; }
  45. public int Index { get; set; }
  46. public string ManufacturerName { get; private set; }
  47. public bool IsFindByIp { get; private set; }
  48. public string ModelName { get; private set; }
  49. public string SerialNumber { get; private set; }
  50. public string CameraIp { get; private set; }
  51. public CameraType CameraType { get; private set; }
  52. MvCameraAcqTool.MvCameraAcqTool mvCameraAcq;
  53. public MyCamera.MV_CC_DEVICE_INFO CameraInfo { get; private set; }
  54. public UInt32 ImageWidth { get; private set; }
  55. public UInt32 ImageHeight { get; private set; }
  56. public MvGvspPixelType PixelType { get; private set; }
  57. private bool _IsGrabbing;
  58. /// <summary>
  59. /// 正在采集
  60. /// </summary>
  61. public bool IsGrabbing
  62. {
  63. get { return _IsGrabbing; }
  64. private set { SetProperty(ref _IsGrabbing, value); }
  65. }
  66. private ICogImage _Image;
  67. public ICogImage Image
  68. {
  69. get { return _Image; }
  70. private set { SetProperty(ref _Image, value); }
  71. }
  72. public bool IsConnected { get; private set; }
  73. private bool IsHaveCamera = false;
  74. /// <summary>
  75. /// 采集用时
  76. /// </summary>
  77. public TimeSpan TotalTime { get; private set; }
  78. /// <summary>
  79. /// 错误信息
  80. /// </summary>
  81. public string ErrorMessage { get; private set; }
  82. #endregion
  83. #region 事件
  84. public event Action<ICogImage, TimeSpan, string> ImageCallbackEvent;
  85. public event Action<Guid, bool> CameraConnectChangedEvent;
  86. #endregion
  87. public MvCamera(Guid id,int index, string name, string serialNumber,string cameraip,bool isFindByIp)
  88. {
  89. ID = id;
  90. Name = serialNumber;
  91. Index = index;
  92. CameraIp=cameraip;
  93. SerialNumber = serialNumber;
  94. IsFindByIp= isFindByIp;
  95. mvCameraAcq = new MvCameraAcqTool.MvCameraAcqTool();
  96. MyCamera.MV_CC_DEVICE_INFO_LIST stDeviceList = default(MyCamera.MV_CC_DEVICE_INFO_LIST);
  97. mvCameraAcq.EnumDeivce(ref stDeviceList);
  98. MyCamera.MV_CC_DEVICE_INFO device = default(MyCamera.MV_CC_DEVICE_INFO);
  99. for (int i = 0; i < stDeviceList.nDeviceNum; i++)
  100. {
  101. device = (MyCamera.MV_CC_DEVICE_INFO)Marshal.PtrToStructure(stDeviceList.pDeviceInfo[i], typeof(MyCamera.MV_CC_DEVICE_INFO));
  102. if (device.nTLayerType == CSystem.MV_GIGE_DEVICE)
  103. {
  104. MV_GIGE_DEVICE_INFO stGigEDeviceInfo = (MV_GIGE_DEVICE_INFO)MyCamera.ByteToStruct(device.SpecialInfo.stGigEInfo, typeof(MV_GIGE_DEVICE_INFO));
  105. uint nIp1 = ((stGigEDeviceInfo.nCurrentIp & 0xff000000) >> 24);
  106. uint nIp2 = ((stGigEDeviceInfo.nCurrentIp & 0x00ff0000) >> 16);
  107. uint nIp3 = ((stGigEDeviceInfo.nCurrentIp & 0x0000ff00) >> 8);
  108. uint nIp4 = (stGigEDeviceInfo.nCurrentIp & 0x000000ff);
  109. string ip= string.Format("{0}.{1}.{2}.{3}", nIp1, nIp2, nIp3, nIp4);
  110. if (IsFindByIp)
  111. {
  112. if (CameraIp == ip)
  113. {
  114. ManufacturerName = stGigEDeviceInfo.chManufacturerName;
  115. ModelName = stGigEDeviceInfo.chModelName;
  116. SerialNumber = stGigEDeviceInfo.chSerialNumber;
  117. CameraType = CameraType.GIGE;
  118. CameraInfo = device;
  119. IsHaveCamera = true;
  120. break;
  121. }
  122. }
  123. else
  124. {
  125. if (string.Equals(stGigEDeviceInfo.chSerialNumber, serialNumber))
  126. {
  127. ManufacturerName = stGigEDeviceInfo.chManufacturerName;
  128. ModelName = stGigEDeviceInfo.chModelName;
  129. SerialNumber = stGigEDeviceInfo.chSerialNumber;
  130. CameraType = CameraType.GIGE;
  131. CameraInfo = device;
  132. IsHaveCamera = true;
  133. break;
  134. }
  135. }
  136. }
  137. else if (device.nTLayerType == CSystem.MV_USB_DEVICE)
  138. {
  139. MV_USB3_DEVICE_INFO usbInfo = (MV_USB3_DEVICE_INFO)MyCamera.ByteToStruct(device.SpecialInfo.stUsb3VInfo, typeof(MV_USB3_DEVICE_INFO));
  140. if (string.Equals(usbInfo.chSerialNumber, serialNumber))
  141. {
  142. ManufacturerName = usbInfo.chManufacturerName;
  143. ModelName = usbInfo.chModelName;
  144. SerialNumber = usbInfo.chSerialNumber;
  145. CameraType = CameraType.USB;
  146. CameraInfo = device;
  147. IsHaveCamera = true;
  148. break;
  149. }
  150. }
  151. }
  152. IsConnected = false;
  153. }
  154. #region 方法
  155. /// <summary>
  156. /// 获取设备
  157. /// </summary>
  158. /// <returns></returns>
  159. public static CameraInfo[] GetDevices()
  160. {
  161. List<CameraInfo> cameras = new List<CameraInfo>();
  162. try
  163. {
  164. if (!CheckSoftwareInstalled().isInstalled)
  165. {
  166. LogHelper.WriteLogInfo(Lang.未安装MVS);
  167. return cameras.ToArray();
  168. }
  169. List<CCameraInfo> m_ltDeviceList = new List<CCameraInfo>();
  170. int nRet = CSystem.EnumDevices(CSystem.MV_GIGE_DEVICE | CSystem.MV_USB_DEVICE, ref m_ltDeviceList);
  171. if (0 != nRet)
  172. {
  173. return cameras.ToArray();
  174. }
  175. for (int i = 0; i < m_ltDeviceList.Count; i++)
  176. {
  177. if (m_ltDeviceList[i].nTLayerType == CSystem.MV_GIGE_DEVICE)
  178. {
  179. CGigECameraInfo gigeInfo = (CGigECameraInfo)m_ltDeviceList[i];
  180. uint nIp1 = ((gigeInfo.nCurrentIp & 0xff000000) >> 24);
  181. uint nIp2 = ((gigeInfo.nCurrentIp & 0x00ff0000) >> 16);
  182. uint nIp3 = ((gigeInfo.nCurrentIp & 0x0000ff00) >> 8);
  183. uint nIp4 = (gigeInfo.nCurrentIp & 0x000000ff);
  184. string ip = string.Format("{0}.{1}.{2}.{3}", nIp1, nIp2, nIp3, nIp4);
  185. cameras.Add(new CameraInfo()
  186. {
  187. CameraNo= i + 1,
  188. CameraName = gigeInfo.UserDefinedName,
  189. CameraBrand = CameraBrand.HikRobot_MVS,
  190. CameraType = CameraType.GIGE,
  191. ManufacturerName = gigeInfo.chManufacturerName,
  192. Model = gigeInfo.chModelName,
  193. SerialNumber = gigeInfo.chSerialNumber,
  194. CameraIp = ip,
  195. IsFindByIp=true,
  196. });
  197. }
  198. else if (m_ltDeviceList[i].nTLayerType == CSystem.MV_USB_DEVICE)
  199. {
  200. CUSBCameraInfo usbInfo = (CUSBCameraInfo)m_ltDeviceList[i];
  201. cameras.Add(new Models.CameraInfo()
  202. {
  203. CameraNo = i + 1,
  204. CameraName = usbInfo.UserDefinedName,
  205. CameraBrand = CameraBrand.HikRobot_MVS,
  206. CameraType = CameraType.USB,
  207. ManufacturerName = usbInfo.chManufacturerName,
  208. Model = usbInfo.chModelName,
  209. SerialNumber = usbInfo.chSerialNumber,
  210. CameraIp = "",
  211. });
  212. }
  213. else if (m_ltDeviceList[i].nTLayerType == CSystem.MV_CAMERALINK_DEVICE)
  214. {
  215. CCamLCameraInfo Info = (CCamLCameraInfo)m_ltDeviceList[i];
  216. cameras.Add(new Models.CameraInfo()
  217. {
  218. CameraNo = i + 1,
  219. CameraName = Info.chModelName,
  220. CameraBrand = CameraBrand.HikRobot_MVS,
  221. CameraType = CameraType.USB,
  222. ManufacturerName = Info.chManufacturerName,
  223. Model = Info.chModelName,
  224. SerialNumber = Info.chSerialNumber,
  225. CameraIp = "",
  226. });
  227. }
  228. }
  229. }
  230. catch (Exception ex)
  231. {
  232. LogHelper.WriteLogError(Lang.搜索海康相机列表时出错, ex);
  233. }
  234. return cameras.ToArray();
  235. }
  236. /// <summary>
  237. /// 检查相机软件是否安装
  238. /// </summary>
  239. /// <returns></returns>
  240. public static (bool isInstalled, string version) CheckSoftwareInstalled()
  241. {
  242. string softwareName = "MVS";
  243. string softwareVersion = "4.4.0";
  244. string[] registryPaths = new[]
  245. {
  246. @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall",
  247. @"SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall"
  248. };
  249. foreach (var path in registryPaths)
  250. {
  251. using (RegistryKey key = Registry.LocalMachine.OpenSubKey(path))
  252. {
  253. if (key == null) continue;
  254. foreach (string subKeyName in key.GetSubKeyNames())
  255. {
  256. using (RegistryKey subKey = key.OpenSubKey(subKeyName))
  257. {
  258. string displayName = subKey.GetValue("DisplayName")?.ToString();
  259. if (displayName != null && displayName.ToUpper().Trim()==softwareName.ToUpper())
  260. {
  261. string version = subKey.GetValue("DisplayVersion")?.ToString();
  262. Version v1 = new Version(version);
  263. Version v2 = new Version(softwareVersion);
  264. if (v1 >= v2)
  265. {
  266. return (true, version);
  267. }
  268. else
  269. {
  270. return (false, version);
  271. }
  272. }
  273. }
  274. }
  275. }
  276. }
  277. return (false, "");
  278. }
  279. /// <summary>
  280. /// 打开相机
  281. /// </summary>
  282. /// <returns></returns>
  283. /// <exception cref="Exception"></exception>
  284. public bool OpenDevice()
  285. {
  286. _operationSemaphore.Wait();
  287. try
  288. {
  289. if (!IsHaveCamera)
  290. {
  291. mvCameraAcq = new MvCameraAcqTool.MvCameraAcqTool();
  292. MyCamera.MV_CC_DEVICE_INFO_LIST stDeviceList = default(MyCamera.MV_CC_DEVICE_INFO_LIST);
  293. mvCameraAcq.EnumDeivce(ref stDeviceList);
  294. MyCamera.MV_CC_DEVICE_INFO device = default(MyCamera.MV_CC_DEVICE_INFO);
  295. for (int i = 0; i < stDeviceList.nDeviceNum; i++)
  296. {
  297. device = (MyCamera.MV_CC_DEVICE_INFO)Marshal.PtrToStructure(stDeviceList.pDeviceInfo[i], typeof(MyCamera.MV_CC_DEVICE_INFO));
  298. if (device.nTLayerType == CSystem.MV_GIGE_DEVICE)
  299. {
  300. MV_GIGE_DEVICE_INFO stGigEDeviceInfo = (MV_GIGE_DEVICE_INFO)MyCamera.ByteToStruct(device.SpecialInfo.stGigEInfo, typeof(MV_GIGE_DEVICE_INFO));
  301. uint nIp1 = ((stGigEDeviceInfo.nCurrentIp & 0xff000000) >> 24);
  302. uint nIp2 = ((stGigEDeviceInfo.nCurrentIp & 0x00ff0000) >> 16);
  303. uint nIp3 = ((stGigEDeviceInfo.nCurrentIp & 0x0000ff00) >> 8);
  304. uint nIp4 = (stGigEDeviceInfo.nCurrentIp & 0x000000ff);
  305. string ip = string.Format("{0}.{1}.{2}.{3}", nIp1, nIp2, nIp3, nIp4);
  306. if (IsFindByIp)
  307. {
  308. if (CameraIp == ip)
  309. {
  310. ManufacturerName = stGigEDeviceInfo.chManufacturerName;
  311. ModelName = stGigEDeviceInfo.chModelName;
  312. SerialNumber = stGigEDeviceInfo.chSerialNumber;
  313. CameraType = CameraType.GIGE;
  314. CameraInfo = device;
  315. IsHaveCamera = true;
  316. break;
  317. }
  318. }
  319. else
  320. {
  321. if (string.Equals(stGigEDeviceInfo.chSerialNumber, SerialNumber))
  322. {
  323. ManufacturerName = stGigEDeviceInfo.chManufacturerName;
  324. ModelName = stGigEDeviceInfo.chModelName;
  325. SerialNumber = stGigEDeviceInfo.chSerialNumber;
  326. CameraType = CameraType.GIGE;
  327. CameraInfo = device;
  328. IsHaveCamera = true;
  329. break;
  330. }
  331. }
  332. }
  333. else if (device.nTLayerType == CSystem.MV_USB_DEVICE)
  334. {
  335. MV_USB3_DEVICE_INFO usbInfo = (MV_USB3_DEVICE_INFO)MyCamera.ByteToStruct(device.SpecialInfo.stUsb3VInfo, typeof(MV_USB3_DEVICE_INFO));
  336. if (string.Equals(usbInfo.chSerialNumber, SerialNumber))
  337. {
  338. ManufacturerName = usbInfo.chManufacturerName;
  339. ModelName = usbInfo.chModelName;
  340. SerialNumber = usbInfo.chSerialNumber;
  341. CameraType = CameraType.USB;
  342. CameraInfo = device;
  343. IsHaveCamera = true;
  344. break;
  345. }
  346. }
  347. }
  348. if (!IsHaveCamera)
  349. {
  350. throw new Exception(Lang.没有发现相机);
  351. }
  352. }
  353. mvCameraAcq.OpenDevice(CameraInfo);
  354. mvCameraAcq.AutoExposure = false;
  355. mvCameraAcq.TriggerMode = false;
  356. if (!IsConnected)
  357. {
  358. CameraConnectChangedEvent?.Invoke(ID, true);
  359. }
  360. IsConnected = mvCameraAcq.bIsOpened;
  361. return IsConnected;
  362. }
  363. finally
  364. {
  365. _operationSemaphore.Release();
  366. }
  367. }
  368. /// <summary>
  369. /// 打开相机异步
  370. /// </summary>
  371. /// <returns></returns>
  372. public Task<bool> OpenDeviceAsync()
  373. {
  374. return Task.Run(() =>
  375. {
  376. return OpenDevice();
  377. });
  378. }
  379. /// <summary>
  380. /// 关闭相机
  381. /// </summary>
  382. public void CloseDevice()
  383. {
  384. // ch:关闭设备 | en:Close Device
  385. _operationSemaphore.Wait();
  386. try
  387. {
  388. mvCameraAcq.CloseDevice();
  389. }
  390. finally
  391. {
  392. _operationSemaphore.Release();
  393. }
  394. }
  395. /// <summary>
  396. /// 采集图像
  397. /// </summary>
  398. /// <returns></returns>
  399. public ICogImage Grab()
  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. }