Adding to the answer from H.B. using an example:
For example if I wanted to use some attached property as a hover
color on a button, can I get the attached property value from the
button's template, and will I be able access the attached property
from the button to set the hover color?
Yes, you sure can. Say that you have an Attached Property called HoverBrush
defined in a class called SomeClass, you can set the value on the instance and bind to it in the template
<StackPanel>
<StackPanel.Resources>
<ControlTemplate x:Key="MyButtonTemplate" TargetType="{x:Type Button}">
<Border x:Name="border" Background="Gray">
<ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="border"
Property="Background"
Value="{Binding RelativeSource={RelativeSource TemplatedParent},
Path=(local:SomeClass.HoverBrush)}"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</StackPanel.Resources>
<Button Content="Blue Hover"
local:SomeClass.HoverBrush="Blue"
Template="{StaticResource MyButtonTemplate}"/>
<Button Content="Green Hover"
local:SomeClass.HoverBrush="Green"
Template="{StaticResource MyButtonTemplate}"/>
</StackPanel>
The attached property in question is defined like this
public class SomeClass
{
public static DependencyProperty HoverBrushProperty =
DependencyProperty.RegisterAttached("HoverBrush",
typeof(Brush),
typeof(SomeClass),
new PropertyMetadata(null));
public static void SetHoverBrush(DependencyObject obj, Brush value)
{
obj.SetValue(HoverBrushProperty, value);
}
public static Brush GetHoverBrush(DependencyObject obj)
{
return (Brush)obj.GetValue(HoverBrushProperty);
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…