我已经创建了我自己的附属财产:
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));
}
然后我尝试使用依赖于它的触发器创建一个样式:
<!--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>
但是我遇到了运行时异常:
Cannot convert the value in attribute 'Property' to object of type 'System.Windows.DependencyProperty'. Error at object 'System.Windows.Trigger' in markup file
如何在样式触发器中访问附加属性的值?我已经尝试过使用带有RelativeSource绑定的DataTrigger,但它没有提取值。
答案 0 :(得分:16)
您的触发器声明没问题,但您附加的财产声明有一个小故障。依赖项属性的所有者类型需要是声明它的类型,而不是您计划将其附加到的类型。所以这个:
DependencyProperty.RegisterAttached("Selectable", typeof(bool), typeof(Label)...
需要改为:
DependencyProperty.RegisterAttached("Selectable", typeof(bool), typeof(LabelExtension)...
^^^^^^^^^^^^^^^^^^^^^^