2013-03-11 152 views
0

首先,我将尝试解释我在做什么。我想画一个棋盘。我有一个用户控制研究用于细胞Silverlight:绑定复杂属性

<Grid x:Name="LayoutRoot"> 
     <Border BorderThickness="0" Margin="0" Background="{Binding CellColor, ElementName=userControl, Mode=TwoWay}"/> 
     <Border x:Name="ValidMoveMarker" BorderThickness="0" Margin="0" Background="#FFC1CAB4" Opacity="0"/> 
     <Image x:Name="img" Source="{Binding source, ElementName=userControl, Mode=TwoWay}" Cursor="Hand"/> 

在代码本CellControl的背后我有2个dpProperties

public eColor? PieceColor 
    { 
     get { return (eColor?)GetValue(PieceColorProperty); } 
     set { SetValue(PieceColorProperty, value);} 
    } 
    public static readonly DependencyProperty PieceColorProperty = DependencyProperty.Register("PieceColor", typeof(eColor?), typeof(CellControl), null); 


    public eType? PieceType 
    { 
     get { return (eType?)GetValue(PieceTypeProperty); } 
     set { SetValue(PieceTypeProperty, value);} 
    } 
    public static readonly DependencyProperty PieceTypeProperty = DependencyProperty.Register("PieceType", typeof(eType?), typeof(CellControl), null); 

其中易彩和ETYPE是枚举器。在这里,我也有一个属性

public ImageSource source 
     { 
      get 
      { 
       if (PieceColor == eColor.White) 
       { 
        switch (PieceType) 
        { 
         case eType.Pawn: 
          return new BitmapImage(new Uri("/PO.PC;component/Images/chess_piece_white_pawn_T.png", UriKind.Relative)); 
         case eType.Knight: 
          return new BitmapImage(new Uri("/PO.PC;component/Images/chess_piece_white_knight_T.png", UriKind.Relative)); 
            ... 
         default: 
          return null; 
        } 
       } 
       else 
       { 
        switch (PieceType) 
        { 
         case eType.Pawn: 
        } 
       } 
      } 

现在的问题是,当我尝试使用控制这样

<PP_Controls:CellControl PieceType="{Binding type, Mode=TwoWay}" PieceColor="{Binding color, Mode=TwoWay}" 

其中

private eColor? _color; 
    public eColor? color 
    { 
     get { return _color; } 
     set 
     { 
      _color = value; 
      OnPropertyChanged("color"); 
     } 
    } 

    private eType? _type; 
    public eType? type 
    { 
     get { return _type; } 
     set 
     { 
      _type = value; 
      OnPropertyChanged("type"); 
     } 
    } 

空话发生。但如果我使用这样的控制

<PP_Controls:CellControl PieceType="Bishop" PieceColor="Black" 

它是完美的工作。我在装订中错过了什么吗?这是因为“源”属性不是依赖属性本身?我该如何解决我的问题?

回答

0

你的目标属性是依赖属性,并且源属性是CLR性能实现INotifyPropertyChanged,使你的绑定{Binding type}等应该努力 - 假设DataContext你“与结合使用”与颜色/类型类型属性。在调试器下运行应用程序时,您应该能够通过查看输出窗口来判断这些绑定是否失败(在Silverlight 5中,您还可以使用绑定断点,否则可以将一个简单的ValueConverter应用于绑定以设置调试的断点)。

但是,您的控件的source属性以“懒惰”方式依赖于其他两个属性。您绑定到source属性,但是当属性的计算值发生更改时,不会更新此绑定。您应该添加一个依赖属性更改处理程序到PieceColorPieceType,它调用OnPropertyChanged("source")(或等价地将其转换为DP或通知属性,并显式重新计算该值)。

+0

正是!这是一个关键点“你应该添加一个依赖属性更改处理程序PieceColor和PieceType调用OnPropertyChanged(”源“)”。 另外我缺少PieceType =“{Binding type,Mode = TwoWay}中的ElementName标签” – 2013-03-11 13:17:45