当前位置:   article > 正文

【WPF】MVVM是如何解耦的_mvvm解耦

mvvm解耦

前言

        因为本身对wpf理解不深如果有技术方面的问题希望可以帮忙纠正,谢谢。

1.MVVM是什么

        从百度百科(MVVM_百度百科)可以了解它出现的原因以及优点。它的其中一个优点就是低耦合,这篇文章也是想聊聊.net是如何对Model-View解耦的,因为.net的代码比较复杂,现在只拆出来关键代码来描述。

 2.Wpf中的Binding

        熟悉wpf的朋友都知道wpf中大部分控件都继承自FrameworkElement,FrameworkElement中有一个方法SetBinding

  1. public BindingExpressionBase SetBinding(DependencyProperty dp, BindingBase binding)
  2. {
  3. return BindingOperations.SetBinding(this, dp, binding);
  4. }

        这个方法有两个参数DependencyProperty和BindingBase以及一个返回值BindingExpressionBase,我们简单看下这3个类

        (1)DependencyProperty wpf中的依赖属性 例如:TextBox.TextProperty

  1. public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(TextBox), new FrameworkPropertyMetadata(string.Empty, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault | FrameworkPropertyMetadataOptions.Journal, OnTextPropertyChanged, CoerceText, isAnimationProhibited: true, UpdateSourceTrigger.LostFocus));
  2. public string Text
  3. {
  4. get
  5. {
  6. return (string)GetValue(TextProperty);
  7. }
  8. set
  9. {
  10. SetValue(TextProperty, value);
  11. }
  12. }

        (2)BindingBase wpf中数据绑定的基类,经常使用的Binding就是BindingBase的子类,BindingBase中有一个内部的方法CreateBindingExpression,CreateBindingExpression中直接调用了抽象方法CreateBindingExpressionOverride,主要代码如下

  1. internal BindingExpressionBase CreateBindingExpression(DependencyObject targetObject, DependencyProperty targetProperty)
  2. {
  3. _isSealed = true;
  4. return CreateBindingExpressionOverride(targetObject, targetProperty, null);
  5. }
  6. internal abstract BindingExpressionBase CreateBindingExpressionOverride(DependencyObject targetObject, DependencyProperty targetProperty, BindingExpressionBase owner);

        Binding继承BindingBase重写了CreateBindingExpressionOverride

  1. internal override BindingExpressionBase CreateBindingExpressionOverride(DependencyObject target, DependencyProperty dp, BindingExpressionBase owner)
  2. {
  3. return BindingExpression.CreateBindingExpression(target, dp, this, owner);
  4. }

        可以看到CreateBindingExpressionOverride的返回值为BindingExpressionBase,等下再说这两个方法,先介绍BindingExpressionBase

        (3)BindingExpressionBase 从字面意思可以理解为Binding的表达式,实际上就是存储Binding的值的关系(谁绑定了谁)

        可以看出SetBinding时将控件的依赖属性和要Binding的数据做了一个关系,即BindingExpressionBase,我们知道一个正常的通知要么用委托要么用事件将两个需要相互影响的值关联起来。下面我列举2种形式:

        (1)通知方/被通知方关联目标对象

  1. public class TestVM
  2. {
  3. public event Action<string> VMChanged;
  4. private string vM;
  5. public string VM
  6. {
  7. get => vM;
  8. set
  9. {
  10. vM = value;
  11. VMChanged?.Invoke(vM);
  12. }
  13. }
  14. }
  15. public class MyButton : Button
  16. {
  17. public MyButton()
  18. {
  19. }
  20. public MyButton(TestVM testVM)
  21. {
  22. testVM.VMChanged += TestVM_VMChanged;
  23. }
  24. private void TestVM_VMChanged(string data)
  25. {
  26. this.Content = data;
  27. }
  28. }

        如上方代码所示,可以在通知方增加属性改变事件,在被通知方构造时订阅这个改变事件从而实现值改变,但是这样做会有一个明显的缺点TestVM和MyButton出现和耦合,MyButton需要有一个方法将TestVM传递到类内部,此时MyButton订阅了TestVM的VMChanged事件,那么假如TestVM一直没被回收,MyButton就一直有一个TestVM的引用导致MyButton无法被回收

        (2)借助第3个类

  1. public class Main
  2. {
  3. private MyButton _testButton;
  4. private TestVM _testVM;
  5. public void Init()
  6. {
  7. _testButton = new MyButton();
  8. _testVM = new TestVM();
  9. _testVM.VMChanged += TestVM_VMChanged;
  10. }
  11. private void TestVM_VMChanged(string data)
  12. {
  13. if (_testButton != null)
  14. _testButton.Content = data;
  15. }
  16. public void DisposedTestButton()
  17. {
  18. _testButton = null;
  19. }
  20. public void DisposedTestTestVM()
  21. {
  22. _testVM = null;
  23. }
  24. }

        如上方代码所示,借助第3个类Main来将TestVM和MyButton关联起来,这样的话TestVM和MyButton直接就没有了直接联系,我们单方面去调用DisposedTestButton或者DisposedTestTestVM都是可以将他们回收掉的,这也是我们日常开发所用到最多的处理方式,将两个需要相互或者单方向通知的对象之间的关系转移到第3个类(主页面),当然Binding也是采用这种处理方式,不过由于Binding需要更通用且需要自动回收所以做了一些额外处理

 3.INotifyPropertyChanged

        下面时INotifyPropertyChanged接口的源码

  1. public interface INotifyPropertyChanged
  2. {
  3. event PropertyChangedEventHandler PropertyChanged;
  4. }

        我们日常的用法和MvvmLight中的ObservableObject的用法是一致的,下面贴出ObservableObject的部分源码以及我们的日常实现

  1. public class ObservableObject : INotifyPropertyChanged
  2. {
  3. public event PropertyChangedEventHandler PropertyChanged;
  4. public virtual void RaisePropertyChanged([CallerMemberName] string propertyName = null)
  5. {
  6. this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
  7. }
  8. }
  9. public class TestVM : INotifyPropertyChanged
  10. {
  11. public event Action<string> VMChanged;
  12. private string vM;
  13. public string VM
  14. {
  15. get => vM;
  16. set
  17. {
  18. vM = value;
  19. VMChanged?.Invoke(vM);
  20. NotifyPropertyChanged("VM");
  21. }
  22. }
  23. #region 实现接口
  24. public event PropertyChangedEventHandler PropertyChanged;
  25. public void NotifyPropertyChanged(string propertyName)
  26. {
  27. PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
  28. }
  29. #endregion
  30. }

        当然只是这样还不够,还需要在前台xaml中对他们进行绑定,在将MyButton_Test的上下文设置为指定的对象(TestVM),就可以实现TestVM和MyButton的相互通知了

<local:MyButton x:Name="MyButton_Test" Content="{Binding VM}"/>

        不过我们知道两个事物不可能无缘无故的联系起来,那么必定在Binding的时候做了一些处理,将两个对象关联起来了,下面看源码,由于源码较长只截取关键路径

  1. public sealed class BindingExpression : BindingExpressionBase, IDataBindEngineClient, IWeakEventListener
  2. {
  3. private BindingWorker Worker => _worker;
  4. private void CreateWorker()
  5. {
  6. Invariant.Assert(Worker == null, "duplicate call to CreateWorker");
  7. _worker = new ClrBindingWorker(this, base.Engine);
  8. }
  9. public override void UpdateTarget()
  10. {
  11. if (base.IsDetached)
  12. {
  13. throw new InvalidOperationException(SR.Get("BindingExpressionIsDetached"));
  14. }
  15. if (Worker != null)
  16. {
  17. Worker.RefreshValue();
  18. }
  19. }
  20. }
  21. internal class ClrBindingWorker : BindingWorker
  22. {
  23. private PropertyPathWorker PW => _pathWorker;
  24. internal override void RefreshValue()
  25. {
  26. PW.RefreshValue();
  27. }
  28. }
  29. internal sealed class PropertyPathWorker : IWeakEventListener
  30. {
  31. internal void RefreshValue()
  32. {
  33. for (int i = 1; i < _arySVS.Length; i++)
  34. {
  35. object reference = BindingExpressionBase.GetReference(_arySVS[i].item);
  36. if (!ItemsControl.EqualsEx(reference, RawValue(i - 1)))
  37. {
  38. UpdateSourceValueState(i - 1, null);
  39. return;
  40. }
  41. }
  42. UpdateSourceValueState(Length - 1, null);
  43. }
  44. private void UpdateSourceValueState(int k, ICollectionView collectionView)
  45. {
  46. UpdateSourceValueState(k, collectionView, BindingExpression.NullDataItem, isASubPropertyChange: false);
  47. }
  48. private void UpdateSourceValueState(int k, ICollectionView collectionView, object newValue, bool isASubPropertyChange)
  49. {
  50. //...省略前方代码
  51. for (k++; k < _arySVS.Length; k++)
  52. {
  53. isASubPropertyChange = false;
  54. ICollectionView collectionView2 = _arySVS[k].collectionView;
  55. obj = ((newValue == BindingExpression.NullDataItem) ? RawValue(k - 1) : newValue);
  56. newValue = BindingExpression.NullDataItem;
  57. if (obj == AsyncRequestPending)
  58. {
  59. _status = PropertyPathStatus.AsyncRequestPending;
  60. break;
  61. }
  62. if (!flag && obj == BindingExpressionBase.DisconnectedItem && _arySVS[k - 1].info == FrameworkElement.DataContextProperty)
  63. {
  64. flag = true;
  65. }
  66. ReplaceItem(k, BindingExpression.NullDataItem, obj);
  67. ICollectionView collectionView3 = _arySVS[k].collectionView;
  68. if (collectionView2 != collectionView3 && _host != null)
  69. {
  70. _host.ReplaceCurrentItem(collectionView2, collectionView3);
  71. }
  72. }
  73. //...省略后方代码
  74. }
  75. private void ReplaceItem(int k, object newO, object parent)
  76. {
  77. //...省略前方代码
  78. if (IsDynamic && SVI[k].type != SourceValueType.Direct)
  79. {
  80. Engine.RegisterForCacheChanges(newO, svs.info);
  81. PropertyPath.DowncastAccessor(svs.info, out DependencyProperty dp2, out PropertyInfo pi2, out PropertyDescriptor pd2, out DynamicObjectAccessor _);
  82. INotifyPropertyChanged source2;
  83. if (newO == BindingExpression.StaticSource)
  84. {
  85. Type type2 = (pi2 != null) ? pi2.DeclaringType : pd2?.ComponentType;
  86. if (type2 != null)
  87. {
  88. StaticPropertyChangedEventManager.AddHandler(type2, OnStaticPropertyChanged, SVI[k].propertyName);
  89. }
  90. }
  91. else if (dp2 != null)
  92. {
  93. _dependencySourcesChanged = true;
  94. }
  95. else if ((source2 = (newO as INotifyPropertyChanged)) != null)
  96. {
  97. PropertyChangedEventManager.AddHandler(source2, OnPropertyChanged, SVI[k].propertyName);
  98. }
  99. else if (pd2 != null && newO != null)
  100. {
  101. ValueChangedEventManager.AddHandler(newO, OnValueChanged, pd2);
  102. }
  103. }
  104. //...省略后方代码
  105. }
  106. }
  107. public class PropertyChangedEventManager : WeakEventManager
  108. {
  109. protected override void StartListening(object source)
  110. {
  111. INotifyPropertyChanged notifyPropertyChanged = (INotifyPropertyChanged)source;
  112. notifyPropertyChanged.PropertyChanged += OnPropertyChanged;
  113. }
  114. protected override void StopListening(object source)
  115. {
  116. INotifyPropertyChanged notifyPropertyChanged = (INotifyPropertyChanged)source;
  117. notifyPropertyChanged.PropertyChanged -= OnPropertyChanged;
  118. }
  119. public static void AddHandler(INotifyPropertyChanged source, EventHandler<PropertyChangedEventArgs> handler, string propertyName)
  120. {
  121. if (handler == null)
  122. {
  123. throw new ArgumentNullException("handler");
  124. }
  125. CurrentManager.PrivateAddHandler(source, handler, propertyName);
  126. }
  127. private void PrivateAddHandler(INotifyPropertyChanged source, EventHandler<PropertyChangedEventArgs> handler, string propertyName)
  128. {
  129. AddListener(source, propertyName, null, handler);
  130. }
  131. private void AddListener(INotifyPropertyChanged source, string propertyName, IWeakEventListener listener, EventHandler<PropertyChangedEventArgs> handler)
  132. {
  133. using (base.WriteLock)
  134. {
  135. //...省略前方代码
  136. HybridDictionary hybridDictionary = (HybridDictionary)base[source];
  137. if (hybridDictionary == null)
  138. {
  139. hybridDictionary = (HybridDictionary)(base[source] = new HybridDictionary(caseInsensitive: true));
  140. StartListening(source);
  141. }
  142. //...省略后方代码
  143. }
  144. }
  145. private void OnPropertyChanged(object sender, PropertyChangedEventArgs args)
  146. {
  147. //...省略前方代码
  148. base.DeliverEventToList(sender, args, listenerList);
  149. //...省略后方代码
  150. }
  151. }
  152. public abstract class WeakEventManager : DispatcherObject
  153. {
  154. protected void DeliverEventToList(object sender, EventArgs args, WeakEventManager.ListenerList list)
  155. {
  156. bool flag = list.DeliverEvent(sender, args, base.GetType());
  157. if (flag)
  158. {
  159. this.ScheduleCleanup();
  160. }
  161. }
  162. public override bool DeliverEvent(object sender, EventArgs e, Type managerType)
  163. {
  164. TEventArgs e2 = (TEventArgs)((object)e);
  165. bool flag = false;
  166. int i = 0;
  167. int count = base.Count;
  168. while (i < count)
  169. {
  170. WeakEventManager.Listener listener = base.GetListener(i);
  171. if (listener.Target != null)
  172. {
  173. //eventHandler就是PropertyPathWorker中订阅INotifyPropertyChanged.PropertyChanged事件的方法
  174. EventHandler<TEventArgs> eventHandler = (EventHandler<TEventArgs>)listener.Handler;
  175. if (eventHandler != null)
  176. {
  177. eventHandler(sender, e2);
  178. }
  179. else
  180. {
  181. flag |= base.DeliverEvent(ref listener, sender, e, managerType);
  182. }
  183. }
  184. else
  185. {
  186. flag = true;
  187. }
  188. i++;
  189. }
  190. return flag;
  191. }
  192. }

        可以看到在BindingExpression在调用UpdateTarget时最终会调用PropertyChangedEventManager的StartListening订阅INotifyPropertyChanged的PropertyChanged事件,至此两个绑定的属性产生了联系,只要我们在模型里面调用PropertyChanged就可是通知到对应需要改变的对象的属性,需要注意的是这里分别有一个重要的类和接口(WeakEventManager和IWeakEventListener),我们可以看到WeakEventManager充当的角色就是上面的Main(第三个类)将两个类关系起来,下面我们实现自己的通知时需要用到,由于具体改变属性的代码量比较大并且控件和UI具体怎么交互也不太了解,之后学习DependencyObject和DependencyProperty再详细介绍

        下面是简单的一个调用关系图

 4.根据.Net的实现逻辑实现通知

       说了这么多我们仿照着.net的实现逻辑自己实现一份,下面先贴代码

  1. public interface IMyWeakEventTest
  2. {
  3. event Action<object, string> PropertyChanged;
  4. }

        第一个接口IMyWeakEventTest对应INotifyPropertyChanged

  1. public class MyWeakEventBindingExpTest : IWeakEventListener
  2. {
  3. public MyWeakEventBindingExpTest(DependencyObject dobj, DependencyProperty dp, object obj, string sourceFiled)
  4. {
  5. Target = new WeakReference<DependencyObject>(dobj);
  6. Source = new WeakReference<object>(obj);
  7. DProperty = dp;
  8. SourceFiled = sourceFiled;
  9. }
  10. public DependencyProperty DProperty { get; set; }
  11. public WeakReference<DependencyObject> Target { get; set; }
  12. public WeakReference<object> Source { get; set; }
  13. public string SourceFiled { get; set; }
  14. public object RSource
  15. {
  16. get
  17. {
  18. if (Source.TryGetTarget(out var source))
  19. return source;
  20. return null;
  21. }
  22. }
  23. public DependencyObject RTarget
  24. {
  25. get
  26. {
  27. if (Target.TryGetTarget(out var target))
  28. return (DependencyObject)target;
  29. return null;
  30. }
  31. }
  32. public void UpdateTarget()
  33. {
  34. this.RTarget.SetValue(this.DProperty, this.RSource.GetType().GetProperty(SourceFiled)?.GetValue(this.RSource));
  35. }
  36. public bool ReceiveWeakEvent(Type managerType, object sender, EventArgs e)
  37. {
  38. var myWeakEventArgsTest = e as MyWeakEventArgsTest;
  39. if (myWeakEventArgsTest == null)
  40. return true;
  41. if (myWeakEventArgsTest.Value != SourceFiled)
  42. return true;
  43. this.UpdateTarget();
  44. return true;
  45. }
  46. }

        第二个MyWeakEventBindingExpTest对应BindingExpression和PropertyPathWorker,由于现在只说原理所以将BindingExpression和PropertyPathWorker的功能合并了,这里可以看到Source(数据源)和Target(目标)我们用了WeakReference(弱引用类)目的是为了内存的自动释放

  1. public class MyWeakEventManagerTest : WeakEventManager
  2. {
  3. protected override void StartListening(object source)
  4. {
  5. var weTest = source as IMyWeakEventTest;
  6. if (weTest != null)
  7. weTest.PropertyChanged += WeTest_PropertyChanged;
  8. }
  9. private void WeTest_PropertyChanged(object arg1, string arg2)
  10. {
  11. base.DeliverEvent(arg1, new MyWeakEventArgsTest() { Value = arg2 });
  12. }
  13. protected override void StopListening(object source)
  14. {
  15. var weTest = source as IMyWeakEventTest;
  16. if (weTest != null)
  17. weTest.PropertyChanged -= WeTest_PropertyChanged;
  18. }
  19. public void AddLinstener(object source, IWeakEventListener eventListener)
  20. {
  21. var myBindingExp = eventListener as MyWeakEventBindingExpTest;
  22. MyWeakEventTestExtension.SetWeakListener(myBindingExp.RTarget, myBindingExp);
  23. myBindingExp.UpdateTarget();
  24. this.ProtectedAddListener(source, eventListener);
  25. }
  26. public void RemoveLinstener(object source, IWeakEventListener eventListener)
  27. {
  28. this.ProtectedRemoveListener(source, eventListener);
  29. }
  30. }

        第三个MyWeakEventManagerTest对应PropertyChangedEventManager

  1. public class MyWeakEventTestExtension
  2. {
  3. public static readonly DependencyProperty WeakListenerProperty = DependencyProperty.RegisterAttached("WeakListener", typeof(IWeakEventListener), typeof(MyWeakEventTestExtension), new PropertyMetadata(null));
  4. public static void SetWeakListener(DependencyObject element, IWeakEventListener value) => element.SetValue(WeakListenerProperty, value);
  5. public static IWeakEventListener GetWeakListener(DependencyObject element) => (IWeakEventListener)element.GetValue(WeakListenerProperty);
  6. }

        第四个是一个扩展类,主要是为了在Target(即控件)存储IWeakEventListener即MyWeakEventBindingExpTest避免MyWeakEventBindingExpTest被回收

        上面代码和框架提供的结构基本一致同样用到了WeakEventManager和IWeakEventListene先看类名WeakEvent(弱事件)Manager(管理员),我们都知道弱引用它会在系统需要内存时被回收,WeakEventManager也是同样的,WeakEventManager内部有一个虚方法Purge(清除),会对无用的订阅进行释放,IWeakEventListene就是为WeakEventManager服务的

  1. protected virtual bool Purge(object source, object data, bool purgeAll)
  2. {
  3. bool result = false;
  4. bool flag = purgeAll || source == null;
  5. if (!flag)
  6. {
  7. ListenerList list = (ListenerList)data;
  8. if (ListenerList.PrepareForWriting(ref list) && source != null)
  9. {
  10. Table[this, source] = list;
  11. }
  12. if (list.Purge())
  13. {
  14. result = true;
  15. }
  16. flag = list.IsEmpty;
  17. }
  18. if (flag && source != null)
  19. {
  20. StopListening(source);
  21. if (!purgeAll)
  22. {
  23. Table.Remove(this, source);
  24. result = true;
  25. }
  26. }
  27. return result;
  28. }

 5.测试自定义通知,内存分析

        我们先简单的搭一个测试例子

         后台代码如下

  1. public partial class Window13 : Window
  2. {
  3. #region 私有成员
  4. //索引
  5. private int _index = 1;
  6. //通知模型列表
  7. private List<MyWeakEventTest> _myWeakEventTests = new List<MyWeakEventTest>();
  8. //弱引用管理
  9. private MyWeakEventManagerTest _myWeakEventManagerTest = new MyWeakEventManagerTest();
  10. #endregion
  11. public Window13()
  12. {
  13. InitializeComponent();
  14. Button_TestEdit_0.Click += Button_TestEdit_0_Click;
  15. Button_ClearView.Click += Button_ClearView_Click;
  16. Button_ClearModel.Click += Button_ClearModel_Click;
  17. Button_GC.Click += Button_GC_Click;
  18. Button_Rest.Click += Button_Rest_Click;
  19. reset();
  20. }
  21. #region 控件事件
  22. /// <summary>
  23. /// 重置视图
  24. /// </summary>
  25. private void Button_Rest_Click(object sender, RoutedEventArgs e)
  26. {
  27. reset();
  28. }
  29. /// <summary>
  30. /// GC
  31. /// </summary>
  32. private void Button_GC_Click(object sender, RoutedEventArgs e)
  33. {
  34. GC.Collect();
  35. }
  36. /// <summary>
  37. /// 清除模型即_myWeakEventTests
  38. /// </summary>
  39. private void Button_ClearModel_Click(object sender, RoutedEventArgs e)
  40. {
  41. _myWeakEventTests.Clear();
  42. }
  43. /// <summary>
  44. /// 清除视图即WrapPanel中的TextBox
  45. /// </summary>
  46. private void Button_ClearView_Click(object sender, RoutedEventArgs e)
  47. {
  48. WrapPanel_Default.Children.Clear();
  49. }
  50. /// <summary>
  51. /// 编辑_myWeakEventTests列表中第一个元素的WTest
  52. /// </summary>
  53. private void Button_TestEdit_0_Click(object sender, RoutedEventArgs e)
  54. {
  55. _myWeakEventTests[0].WTest = $"测试修改{_index}";
  56. _index++;
  57. }
  58. #endregion
  59. #region 辅助方法
  60. /// <summary>
  61. /// 重置视图即清除WrapPanel中的TextBox并重新添加
  62. /// </summary>
  63. private void reset()
  64. {
  65. _myWeakEventTests.Clear();
  66. WrapPanel_Default.Children.Clear();
  67. for (int i = 0; i < 30; i++)
  68. {
  69. var myWeakEventTest = new MyWeakEventTest() { WTest = i.ToString() };
  70. MyTextBox textBox = new MyTextBox() { Width = 100, Height = 30, Text = $"a{i}" };
  71. _myWeakEventManagerTest.AddLinstener(myWeakEventTest, new MyWeakEventBindingExpTest(textBox, MyTextBox.TextProperty, myWeakEventTest, "WTest"));
  72. _myWeakEventTests.Add(myWeakEventTest);
  73. WrapPanel_Default.Children.Add(textBox);
  74. }
  75. }
  76. #endregion
  77. }
  78. public class MyWeakEventTest : IMyWeakEventTest
  79. {
  80. private string _wTest;
  81. public string WTest
  82. {
  83. get => _wTest;
  84. set
  85. {
  86. _wTest = value;
  87. PropertyChanged?.Invoke(this, nameof(WTest));
  88. }
  89. }
  90. public event Action<object, string> PropertyChanged;
  91. }

        五个功能按钮的功能如字面意思,具体在代码注释中体现,代码创建了一个自定义的弱引用管理类(MyWeakEventManagerTest)以及一个通知模型列表(List<MyWeakEventTest>),窗口加载时向WrapPanel中增加了30个TextBox,并调用了MyWeakEventManagerTest的AddLinstener,这一步相当于SetBinding在AddLinstener时我们将MyWeakEventBindingExpTest设置到TextBox的附加属性WeakListenerProperty上并且更新目标,同时订阅IMyWeakEventTest.PropertyChanged。

        这时如果我们点击按钮"测试修改[0]",代码执行取_myWeakEventTests索引为0的值并设置WTest为[$"测试修改{_index}"],经过MyWeakEventManagerTest的中转最终执行了MyWeakEventBindingExpTest.ReceiveWeakEvent,目前MyWeakEventBindingExpTest中保存了Source、Target以及DProperty,同时ReceiveWeakEvent将我们修改的属性名给到了,那么顺理成章的将Target的DProperty修改为新的Source的值。

        说了这么多那么怎么证明它们之间没有耦合,下面通过内存变化来分析

        此时我们截取下内存快照,可以看到各个对象的计数, MyWeakEventTest(模型Source)、MyTextBox(控件Target)、MyWeakEventBindingExpTest(关系及通知管理)都是30个,和我们创建的相符,这个时候我们点击“清除View”即将MyTextBox移除,然后重新截取内存快照

        可以发现MyTextBox和 MyWeakEventBindingExpTest已经被回收,可以通过对象引用差异对比计数变化都为-30

         这时点击“重置”验证清除Model即将MyWeakEventTest移除,然后重新截取内存快照

        可以看到MyWeakEventTest已经被回收

6.总结

        之前看别人的博客,说代码语言不重要重要的是编程逻辑和思想,现在发现越来越是这个味儿了,之后有时间学习DependencyObject和DependencyProperty再分享

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Gausst松鼠会/article/detail/327434
推荐阅读
相关标签
  

闽ICP备14008679号