2013-03-11 124 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