2010-08-18 93 views
2

我在類似的問題看這裏SO,沒能得到解決,所以這裏是我的交易:WPF自定義附加屬性

**我有以下類:**

public static class ControlSecurity 
{ 
    public static readonly DependencyProperty IsSecuredProperty = 
     DependencyProperty.RegisterAttached(
      "IsSecured", 
      typeof (bool), 
      typeof (FrameworkElement), 
      new PropertyMetadata(false)); 

    [AttachedPropertyBrowsableForType(typeof(Control))] 
    public static bool GetIsSecured(FrameworkElement ctl) 
    { 
     return (bool)ctl.GetValue(IsSecuredProperty); 
    } 

    public static void SetIsSecured(FrameworkElement ctl, bool value) 
    { 
     ctl.SetValue(IsSecuredProperty, value); 
    } 
} 

正如你可以猜測,它增加了Security:ControlSecurity.IsSecured所有FrameworkElement s。

注:Security:點命名空間所有這些類(包括ControlSecurity

所以我實現了這個數據模板&風格對我的控制中的一個:

 <DataTemplate x:Key="SecureButtonTemplate"> 
      <StackPanel Orientation="Horizontal"> 
       <Image x:Name="SecureIcon" Source="pack://application:,,,/Resources/Icons/secure.png" Width="16" Height="16" Visibility="Collapsed" /> 
       <ContentPresenter Content="{Binding}" /> 
      </StackPanel> 
      <DataTemplate.Triggers> 
       <DataTrigger Binding="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Button}}, Path=Security:ControlSecurity.IsSecured}" Value="true"> 
        <Setter TargetName="SecureIcon" Property="Visibility" Value="Visible" /> 
       </DataTrigger> 
      </DataTemplate.Triggers> 
     </DataTemplate> 
     <Style TargetType="{x:Type Button}"> 
      <Setter Property="ContentTemplate" Value="{StaticResource SecureButtonTemplate}" /> 
     </Style> 

這裏的問題在於對DataTrigger的綁定:

{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Button}}, Path=Security:ControlSecurity.IsSecured} 

這個想法是,我想找到父按鈕,並將其綁定到我已定義的Security:ControlSecurity.IsSecured附加屬性。

我試過這個結合約10種不同的變化,我不斷收到一個綁定錯誤有點像這樣:

 
System.Windows.Data Error: 40 : BindingExpression path error: 'Security:ControlSecurity' property not found on 'object' ''Button' (Name='')'. BindingExpression:Path=Security:ControlSecurity.IsSecured; DataItem='Button' (Name=''); target element is 'ContentPresenter' (Name=''); target property is 'NoTarget' (type 'Object') 

我在這一點難倒,並會喜歡從WPF一些見解大師在那裏。

回答

11

只需加括號:

Path=(Security:ControlSecurity.IsSecured) 
+0

好吧,我這樣做,現在我得到一個XAML解析異常與內部異常,指出: 屬性路徑無效。 'ControlSecurity'沒有名爲'IsSecured'的公共屬性。 – Aren 2010-08-18 16:53:12

+0

無視我上面的評論我想到了一個,有錯誤的所有者在我附屬的屬性中定義。 – Aren 2010-08-18 17:22:58

+0

虔誠的宗教信仰,這是我的頭,謝謝 – MrEdmundo 2013-07-25 18:13:13