2009-07-22 87 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); 
    } 
}