The BringToFront Behavior

No Comments July 20, 2010


Are you a WPF history buff? If so you might be familiar with the attached behaviors story. It’s a short saga, but worthy of review. Back in the early days of WPF we were learning the nuances of the new XAML system. The attached property system was an interesting subsystem of WPF, revealing a clever way to add a property to an unrelated object. A few of the XAML pioneers decide to extend this idea to behavior. Their idea was to define a behavior (code) in a class, register it with the Dependency System and then ‘attach’ the behavior to other classes.

The idea had merit so the Expression Blend team brought the concept into Blend 3. They created a sub-classable type called System.Windows.Interactivity.Behavior<UIElement>, which makes it simple to create custom attached behaviors.

I’m constantly thinking of ideas for new behaviors, here’s one for moving an object to the front of the other items in a Panel.

 

public class BringToFrontBehavior : Behavior<Panel>
  {
    protected override void OnAttached()
    {
      base.OnAttached();
      AssociatedObject.Loaded += 
new RoutedEventHandler(AssociatedObject_Loaded); } void AssociatedObject_Loaded(object sender, RoutedEventArgs e) { foreach (var child in AssociatedObject.Children) { child.MouseLeftButtonUp += new MouseButtonEventHandler(child_MouseLeftButtonUp); } } void child_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) { BringToFront(sender); } // call this method to move element to front of ZIndex private void BringToFront(object sender) { Panel parent = (Panel)((FrameworkElement)sender).Parent; int z = GetHighestValue(parent); for (int i = 0; i < parent.Children.Count; i++) { if (sender.Equals(parent.Children[i])) { parent.Children[i].SetValue(Canvas.ZIndexProperty, z); } } } private int GetHighestValue(Panel parent) { int highest = 0; foreach (var child in parent.Children) { var val = (int)child.GetValue(Canvas.ZIndexProperty); if (val > highest) { highest = val; } child.SetValue(Canvas.ZIndexProperty, val - 1); } return highest; } }

No Comments

Have a Comment?