Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.
Il est parfois nécessaire d'être notifié lorsqu'un contrôle n'est plus dans l'arbre graphique de silverlight. Il n'existe pas à l'heure actuelle (c'est à dire dans la beta 2) d'événement unload, cependant, l'événement LayoutUpdated est levé sur les contrôles lorsqu'ils sont enlevés de leur parent. Voici un petit exemple de code. Notez au passage l'utilisation des méthodes d'extension.
namespace SLExtensions
{
using System;
using System.Text;
using System.Windows;
using System.Windows.Browser;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.Generic;
/// <summary>
/// Method extensions for SLExtension framework
/// </summary>
public static class SLExtension
...
/// Determines whether an element is in the visual tree of the current application.
/// <param name="element">The element.</param>
/// <returns>
/// <c>true</c> if element paramter is in visual tree otherwise, <c>false</c>.
/// </returns>
public static bool IsInVisualTree(this FrameworkElement element)
return IsInVisualTree(element, Application.Current.RootVisual as FrameworkElement);
}
/// Determines whether an element is in the visual tree of a given ancestor.
/// <param name="ancestor">The ancestor.</param>
public static bool IsInVisualTree(this FrameworkElement element, FrameworkElement ancestor)
FrameworkElement fe = element;
while (fe != null)
if (fe == ancestor)
return true;
fe = fe.Parent as FrameworkElement;
return false;
<UserControl x:Class="SLExtensions.Showcase.IsInVisualTree"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="400" Height="300">
<Grid x:Name="LayoutRoot" Background="White">
<Rectangle x:Name="rect" Fill="Cornsilk" LayoutUpdated="rect_LayoutUpdated" />
<Button Content="Remove rect" Height="40" VerticalAlignment="Bottom" HorizontalAlignment="Center" Width="100" Click="Button_Click" />
</Grid>
</UserControl>
using SLExtensions;
namespace SLExtensions.Showcase
public partial class IsInVisualTree : UserControl
public IsInVisualTree()
InitializeComponent();
private void Button_Click(object sender, RoutedEventArgs e)
LayoutRoot.Children.Remove(rect);
private void rect_LayoutUpdated(object sender, EventArgs e)
if (!rect.IsInVisualTree())
// Handle unload behavior
xcvcx