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();
}
}
}