2010-03-25 61 views
10

我已经创建了自己的附加属性是这样的:风格触发附加属性

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,但它并没有将值拉过来。

回答

15

你的触发器声明没问题,但你的附属属性声明有一个小故障。依赖项属性的所有者类型必须是声明的类型,而不是您打算附加到的类型。所以这个:

DependencyProperty.RegisterAttached("Selectable", typeof(bool), typeof(Label)... 

需要改变这样的:

DependencyProperty.RegisterAttached("Selectable", typeof(bool), typeof(LabelExtension)... 
                   ^^^^^^^^^^^^^^^^^^^^^^ 
+0

谢谢,我摸索出更改所有者类型为Object解决了这一问题,但我不明白为什么。 –