如果我将一个控件绑定到另一个控件,并且其中一个控件死亡,那么绑定会发生什么情况?
例如,让我们采用编程绑定:
Binding binding = new Binding("MyProperty");
binding.Converter = new BooleanToVisibilityConverter();
binding.Source = myWindow.myObject
myButton.SetBinding(Button.VisibilityProperty, binding);
如果 myWindow 死亡并被垃圾收集,会发生什么...我是否也负责释放绑定,或者它自己知道如何执行此操作?
for example, let's take a programmatic binding:
Binding binding = new Binding("MyProperty");
binding.Converter = new BooleanToVisibilityConverter();
binding.Source = myWindow.myObject
myButton.SetBinding(Button.VisibilityProperty, binding);
What happens if myWindow dies and gets garbage collected... am I responsible for freeing up the binding as well, or does it know how to do that itself?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
对于绑定来说情况并非如此,即使您使用
Source
作为Binding
,也不会出现内存泄漏。要验证这一点,
StackPanel
、一个TextBox
(tb1) 和两个Buttons
TextBox< /code> (tb2)
Binding
,并将Source
设置为 tb2WeakReference
(这不应该如果有泄漏,则进行 GC)它返回 false,源
TextBox
(tb2) 已被垃圾收集,因此我们没有内存泄漏编辑:您还可以移动第一个
TextBox< 的创建/code> 从 Xaml 到代码隐藏并使用两个
WeakReferences
(每个TextBox
一个)并验证两个 textBox 是否正确进行 GC,您将看到这是真的。Xaml
代码隐藏
This is not true for Bindings, you'll have no memory leak even if you use
Source
for theBinding
.To verify this
StackPanel
, aTextBox
(tb1) and twoButtons
in XamlTextBox
(tb2)Binding
on tb1 withSource
set to tb2WeakReference
on tb2 (which shouldn't be GC'd if we have a leak)StackPanel
It returns false, the source
TextBox
(tb2) has been garbage collected so we have no memory leakEdit: You can also move the creation of the first
TextBox
from Xaml to code behind and use twoWeakReferences
(one for eachTextBox
) and verify that both textBoxes get GC'd properly and you'll see that this is true.Xaml
Code Behind
我认为它不会被垃圾收集,因为
这里管理对象生命周期
你仍然有一个指针
绑定。**源**
到它。I think that it will not be garbage collected, as
from here Managing object lifetime
you still have a pointer
binding.**Source**
to it.根据 MSDN :
因此,在您的示例中,myWindow 对象无法被垃圾收集,因为存在从绑定对象到 myWindow 的引用。
According to MSDN :
Therefore, in your example myWindow object cannot be garbage collected since there is a reference from binding object to myWindow.