2

アプリに次のクラスがあるとしましょう。

MainWindow.xaml.cs

public partial class MainWindow : Window
{
    public SolidColorBrush Brush { get; set; } 

    public MainWindow()
    {
        InitializeComponent();
        Brush = new SolidColorBrush(Colors.AliceBlue);
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        Window1 window = new Window1();
        window.DataContext = this;
        window.ShowDialog();
        Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle, (Action)delegate
                                                                           {
                                                                               GC.Collect();
                                                                               GC.WaitForPendingFinalizers();
                                                                               GC.Collect();
                                                                           });
    }

MainWindow.xaml

<Window x:Class="WpfApplication8.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525" >
    <Button Click="Button_Click">Do It</Button>
</Window>

Window1.xaml.cs

public partial class Window1 : Window
{
    public Window1()
    {
        InitializeComponent();
    }

    ~Window1()
    {
        Debug.WriteLine("Window1 Finalized");
    }
}

Window1.xaml

<Window x:Class="WpfApplication8.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="300" Width="300"
        Background="{Binding Brush}">
    <Grid>
        
    </Grid>
</Window>

アプリを起動すると、Do Itボタンをクリックして開いているウィンドウを閉じます-Debug.WriteLine("Window1 Finalized");実行されません。これは、Window1 オブジェクトがまだメモリ内にあり、GC されていないことを意味します。しかし、ブラシ バインディングを削除すると、Window1.xaml「Window1 Finalized」という文字列が出力に表示されます。これは、Window1 オブジェクトが GCed であることを意味します。

バインディングはどのようにオブジェクトをメモリに保持しますか? それはバグですか、それともバインディングの実装方法ですか?

編集 1

Background プロパティの代わりに Foreground プロパティをバインドすると、Window1 がファイナライズされます。したがって、依存関係システムの影響ではなく、Background プロパティの実装の影響のようです。

4

2 に答える 2

1

The window1 is not finalized because there are still references to it from the Binding syntax in its BackGround property.

Although the Binding is OneWay, the fact that there is a binding to MainWindow's Property, means there is a reference to Window1 from Mainwindow (because of the way the dependency system works) - therefore the Window1 isn't a candidate for Garbage Collection (and therefore wont be finalized)

于 2010-11-23T15:35:26.380 に答える
1

同様の問題がありました。作成後にブラシでfreezeメソッドを呼び出すと解決しました。

于 2013-10-22T08:21:55.423 に答える