A quick post about blend behaviors in WPF. A behavior (from the System.Windows.Interactive assembly) allows us to add functionality to elements within the UI tree. An example might better serve to describe what one is and how to write one.
Let’s make things simple and say we have a UI element which we want to fade into the background when not focus. So we can create a class derived from Behavior<>. Looking at the properties on a UIElement this will suffice for our needs so we’ll derive our FadeOnLostFocusBehavior (bit of a mouthful) from Behavior
If we jump straight to the code we get something like
public class FadeOnLoseFocusBehavior : Behavior<UIElement> { private const float FADED = 0.2f; protected override void OnAttached() { AssociatedObject.LostFocus += AssociatedObject_LostFocus; AssociatedObject.GotFocus += AssociatedObject_GotFocus; // this just ensures a default state of faded for the control AssociatedObject.Opacity = FADED; base.OnAttached(); } protected override void OnDetaching() { AssociatedObject.LostFocus -= AssociatedObject_LostFocus; AssociatedObject.GotFocus -= AssociatedObject_GotFocus; base.OnDetaching(); } private void AssociatedObject_LostFocus(object sender, RoutedEventArgs e) { AssociatedObject.Opacity = FADED; } private void AssociatedObject_GotFocus(object sender, RoutedEventArgs e) { AssociatedObject.Opacity = 1; } }
The above is very simple. When we attach the behavior to the UIElement we connect to the required events on the AssociatedObject. When we detach from the UIElement we detach from the events on the AssociatedObject. The rest is self-explanatory.
The XAML for this example would look like
<Button Content="Cancel" Width="80" Margin="3" > <i:Interaction.Behaviors> <controls:FadeOnLoseFocusBehavior /> </i:Interaction.Behaviors> </Button>