Style Trigger on Attached Property
I have created my own Attache开发者_如何学God Property like this:
public static class LabelExtension
{
public static bool GetSelectable(DependencyObject obj)
{
return (bool)obj.GetValue(SelectableProperty);
}
public static void SetSelectable(DependencyObject obj, bool value)
{
obj.SetValue(SelectableProperty, value);
}
// Using a DependencyProperty as the backing store for Selectable. This enables animation, styling, binding, etc...
public static readonly DependencyProperty SelectableProperty =
DependencyProperty.RegisterAttached("Selectable", typeof(bool), typeof(Label), new UIPropertyMetadata(false));
}
And then I'm trying to create a style with a trigger that depends on it:
<!--Label-->
<Style TargetType="{x:Type Label}">
<Style.Triggers>
<Trigger Property="Util:LabelExtension.Selectable" Value="True">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Label}">
<TextBox IsReadOnly="True" Text="{TemplateBinding Content}" />
</ControlTemplate>
</Setter.Value>
</Setter>
</Trigger>
</Style.Triggers>
</Style>
But I'm getting a run time exception:
Cannot convert the value in attribute 'Property' to object of type 'System.Windows.DependencyProperty'. Error at object 'System.Windows.Trigger' in markup file
How can I access the value of the attached property in a style trigger? I have tried using a DataTrigger with a RelativeSource binding but it wasn't pulling the value through.
Your trigger declaration is fine, but your attached property declaration has a glitch. The owner type of a dependency property needs to be the type that declares it, not the type you plan to attach it to. So this:
DependencyProperty.RegisterAttached("Selectable", typeof(bool), typeof(Label)...
needs to change to this:
DependencyProperty.RegisterAttached("Selectable", typeof(bool), typeof(LabelExtension)...
^^^^^^^^^^^^^^^^^^^^^^
精彩评论