I’m trying to determine if Attached Behaviors are something we need in building controls for the forms in our application.
Hence, I not only want to know how to create Attached Behaviors but want to see real instances in which they are used to solve problems. I used this MSDN article to create a UserControl with an attached property in a way that I think would be useful, namely, a stackpanel in which certain child elements are either highlighted or not highlighted.
This example runs fine, but where do I put the logic to highlight or not highlight (e.g. change the background color) of the child elements?
XAML:
<Window x:Class="TestAttachedProperties2343.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:TestAttachedProperties2343"
Title="Window1" Height="300" Width="300">
<Grid>
<local:ExtendedStackPanel>
<TextBlock local:ExtendedStackPanel.IsHighlighted="True" Text="text1"/>
<TextBox local:ExtendedStackPanel.IsHighlighted="False" Text="text2"/>
<TextBox local:ExtendedStackPanel.IsHighlighted="True" Text="text3"/>
</local:ExtendedStackPanel>
</Grid>
</Window>
Code Behind:
using System.Windows;
using System.Windows.Controls;
using System.ComponentModel;
using System;
namespace TestAttachedProperties2343
{
public partial class ExtendedStackPanel : StackPanel
{
public static readonly DependencyProperty IsHighlightedProperty = DependencyProperty.RegisterAttached(
"IsHighlighted",
typeof(Boolean),
typeof(ExtendedStackPanel),
new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.AffectsRender));
public static void SetIsHighlighted(UIElement element, Boolean value)
{
element.SetValue(IsHighlightedProperty, value);
}
public static Boolean GetIsHighlighted(UIElement element)
{
return (Boolean)element.GetValue(IsHighlightedProperty);
}
public ExtendedStackPanel()
{
InitializeComponent();
}
}
}
Here is a real altough very simple example: an attached behavior that shows a message when a user clicks a button. The message can be customized via a dependency property in the behavior itself.
The behavior code:
The XAML that uses the behavior:
They key here is that you must override the
OnAttachedandOnDetachedmethods. Here you attach/detach handlers to whatever events you want to control in the associated element, and do whatever you want in the handlers. It is a very powerful and flexible way for adding interactivity to visual controls.Update
The base
Behavior<>class is in theSystem.Windows.Interactivity.dllassembly which is not part of the Silverligh runtime, but is installed with Microsoft Expression Blend 3. It seems anyway that this assembly can be freely redistributed (see here: http://social.expression.microsoft.com/Forums/en-US/blend/thread/8523aec4-1a10-4864-8ad4-f95a3627bb4a)