Friday, January 24, 2014

Attaching to an Event Trigger in Silverlight

There was a case in one of my projects to get notified whenever a Side Panel Visibility is changed.

For example, when a Panel Visibility state changes from "Collapsed" to "Visible" or from "Visible" to "Collapsed" we wanted a function to be called.

Here is the code to achieve this.

This line tells how to register it.

RegisterForNotification("Visibility", SidePanel, SidePanelVisibilityChanged);

Here is the function "RegisterForNotification".

public void RegisterForNotification(string propertyName, FrameworkElement element, PropertyChangedCallback callback)
{//Bind to a depedency property
Binding b = new Binding(propertyName) { Source = element };

var prop = System.Windows.DependencyProperty.RegisterAttached( "ListenAttached"+propertyName, typeof(object), typeof(UserControl), new System.Windows.PropertyMetadata(callback));
 
element.SetBinding(prop, b);
}

This is the callback function which will be called whenever the visibility state changes.

private void SidePanelVisibilityChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{  if (e.NewValue != null)
  {   if (e.NewValue.ToString() == "Collapsed")
   {     // Do something for collapsed... 
    }
  }
}

Hope this helps you.

Enjoy coding !

Cheers
Adam 
 
 

No comments:

Post a Comment

All Blogs so far ...