2009-07-22 90 views
1

我想將一個屬性(Button.Background)綁定到我的自定義附加屬性上的屬性。WPF似乎沒有找到一個自定義附加屬性

在C#文件我有

public static class Square 
{ 
    public static readonly DependencyProperty PlayerProperty = 
     DependencyProperty.RegisterAttached("Player", typeof(Player), 
      typeof(UIElement), new FrameworkPropertyMetadata(null)); 

    public static Player GetPlayer(UIElement element) 
    { 
     return (Player)element.GetValue(PlayerProperty); 
    } 

    public static void SetPlayer(UIElement element, Player player) 
    { 
     element.SetValue(PlayerProperty, player); 
    } 

    // Other attached properties 
} 

我的XAML的一個片段是

<Grid Name="board" Grid.Row="1" Grid.Column="1"> 
    <Grid.Resources> 
     <Style TargetType="{x:Type Button}"> 
      <Setter Property="Height" Value="20" /> 
      <Setter Property="Width" Value="20" /> 
      <Setter Property="BorderThickness" Value="3" /> 
      <Setter Property="Background" 
       Value="{Binding Path=(l:Square.Player).Brush, Mode=OneWay}" /> 
     </Style> 
    </Grid.Resources> 
</Grid> 

這是錯誤我得到:

不能把字符串轉換 「(L :Square.Player).Brush屬性 '路徑' 類型的對象'System.Windows.Prope rtyPath」。 屬性路徑無效。 'Square' 沒有任何公共財產,名稱爲 'Player'。在 標記文件 「Gobang.Gui;組件/ mainwindow.xaml」錯誤在對象 「System.Windows.Data.Binding」 線148的位置59

但是,由於播放器是附加屬性是在Square上,上面的代碼應該可行,對吧?

此外,當我改變我的預標籤碼的標籤,一切都很

回答

4

我相信你的附屬物應該指定Square作爲所有者而不是UIElement。

public static readonly DependencyProperty PlayerProperty = 
    DependencyProperty.RegisterAttached("Player", typeof(Player), 
     typeof(Square), new FrameworkPropertyMetadata(null)); 
+0

這就是我沒有閱讀智能感知工具提示,感嘆。綁定不起作用(背景不變),但這應該是我明天看到的一件愚蠢的事情。非常感謝,我在這上面浪費了很多時間。 – Jamie 2009-07-22 14:53:49

-1

不能建立在你這樣做的方式結合 - 您將需要SquarePlayer的實例綁定到那個。

+0

我並不想綁定到廣場的一個實例繼承,廣場是我的附加屬性聲明。 – Jamie 2009-07-22 14:06:35

0

我得到它的工作。 注:它是一個只讀屬性,輔助類必須從DO

public class Helper : DependencyObject 
{ 
    public static readonly DependencyPropertyKey IsExpandedKey = DependencyProperty.RegisterAttachedReadOnly(
     "IsExpanded", typeof(bool), typeof(Helper), new FrameworkPropertyMetadata(true, FrameworkPropertyMetadataOptions.Inherits)); 

    public static readonly DependencyProperty IsExpandedProperty = IsExpandedKey.DependencyProperty; 

    public static bool GetIsExpanded(DependencyObject d) 
    { 
     return (bool)d.GetValue(IsExpandedKey.DependencyProperty); 
    } 

    internal static void SetIsExpanded(DependencyObject d, bool value) 
    { 
     d.SetValue(IsExpandedKey, value); 
    } 
}