下載app免費領取會員
最近發(fā)現(xiàn)一個有趣的事,通過Window.dataContent來設置綁定以后,
窗體關閉以后 ViewModel 并沒有釋放,再次調用改窗體后,前一個ViewModel才釋放,
或者是程序關閉以后才釋放 ,搞不懂。。。
如果要馬上釋放ViewModel可以在Window關閉以后將DataContent 設置為null ,
這樣ViewModel是可以釋放的
下面是測試代碼,大神請指教!
主窗體:
<Window x:Class="WeakViewModel.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WeakViewModel"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Button Content="Win1" HorizontalAlignment="Left" Margin="367,211,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click"/>
<Button Content="GC" HorizontalAlignment="Left" Margin="128,211,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click_1"/>
</Grid>
</Window>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
TestWindow win = new TestWindow();
win.Owner = this;
win.DataContext = ViewModel.Default;
win.Show();
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
GC.Collect();
}
}
測試窗體:
<Window x:Class="WeakViewModel.TestWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WeakViewModel"
mc:Ignorable="d"
Title="TestWindow" Height="300" Width="300">
<Grid>
<TextBox HorizontalAlignment="Left" Height="23" Margin="96,111,0,0" TextWrapping="Wrap" Text="{Binding Path=Text}" VerticalAlignment="Top" Width="120"/>
</Grid>
</Window>
public partial class TestWindow : Window
{
public TestWindow()
{
InitializeComponent();
Closed += TestWindow_Closed;
}
~ TestWindow()
{
MessageBox.Show("釋放TestWindow");
}
private void TestWindow_Closed(object sender, EventArgs e)
{
//注釋這個行就能看出差別
DataContext = null;
}
}
測試ViewModel:
public class ViewModel
{
private static WeakReference _default = null;
private static object locker = new object();
public static ViewModel Default
{
get
{
if(_default==null||!_default.IsAlive)
{
lock (locker)
{
_default = new WeakReference(new ViewModel());
}
}
return _default.Target as ViewModel;
}
}
private ViewModel()
{
}
~ViewModel()
{
MessageBox.Show("釋放 ViewModel"+Text);
}
private string _text = string.Empty;
public string Text
{
get
{
return _text;
}
set
{
_text = value;
}
}
}
本文版權歸腿腿教學網及原創(chuàng)作者所有,未經授權,謝絕轉載。
上一篇:revit中尺寸標注的新奇方法
下一篇:二次開發(fā)教程:WPF 給控件添加可以綁定的命令
推薦專題