2011-07-29 72 views
4

我想設置一個名爲Sprite的對象的依賴項屬性,一個Sprite包含一個SpriteSheet的字符串,所以我希望能夠傳遞一個Sprite然後該數據用於顯示圖像在我的控制之下。事後使用屬性的依賴屬性?

這是我的嘗試,因爲它代表

public Sprite Sprite 
    { 
     get { return (Quiz.Sprite)GetValue(SpriteProperty); } 
     set { 
      spriteBrush.ImageSource = new BitmapImage(new Uri("/Project;component/" + value.spriteSheet, UriKind.RelativeOrAbsolute)); 

      spriteTransform.TranslateX = -558; 
      spriteTransform.TranslateY = 0; 

      SetValue(SpriteProperty, value); 
     } 
    } 

    public static DependencyProperty SpriteProperty = DependencyProperty.Register(
     "Sprite", typeof(Sprite), typeof(spriteView), new PropertyMetadata(new Quiz.Sprite() { spriteSheet = "wp7_buttons.png" })); 
} 

我如何設定方法來運行的那部分,正如我在依賴項屬性是文檔的SetValue和getValue可能會直接調用時讀過捆綁。

回答

3

這是正確的,你不能使用SetValue來引入任何邏輯。相反,您應該使用PropertyValueChanged處理程序。喜歡的東西:

public Sprite Sprite 
{ 
    get { return (Quiz.Sprite)GetValue(SpriteProperty); } 
    set { SetValue(SpriteProperty, value); } 
} 

private static void OnSpritPropertyValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { 
    var control = d as YourControl; 
    var sprite = e.NewValue as Quiz.Sprite; 

    control.spriteBrush.ImageSource = new BitmapImage(new Uri("/Project;component/" + sprite.spriteSheet, UriKind.RelativeOrAbsolute)); 

    control.spriteTransform.TranslateX = -558; 
    control.spriteTransform.TranslateY = 0; 
} 

public static DependencyProperty SpriteProperty = DependencyProperty.Register(
    "Sprite", typeof(Sprite), typeof(spriteView), 
    new PropertyMetadata(new Quiz.Sprite() { spriteSheet = "wp7_buttons.png" }, OnSpritPropertyValueChanged)); 
3

添加DependencyPropertyChangedEventHandler和代碼從您的二傳手有移動:

public Sprite Sprite 
{ 
    get { return (Quiz.Sprite)GetValue(SpriteProperty); } 
    set { SetValue(SpriteProperty, value); } 
} 

public static DependencyProperty SpriteProperty = DependencyProperty.Register(
"Sprite", typeof(Sprite), typeof(SpriteView), new PropertyMetadata(new Quiz.Sprite() { spriteSheet = "wp7_buttons.png" }, 
SpriteChanged)); 

private static void SpriteChanged(object sender, DependencyPropertyChangedEventArgs e) 
{ 
    SpriteView view = sender as SpriteView; 
    Sprite sprite = e.NewValue as Sprite; 
    if (view != null && sprite != null) 
    { 
     view.spriteBrush.ImageSource = new BitmapImage(new Uri("/Project;component/" + sprite.spriteSheet, UriKind.RelativeOrAbsolute)); 
     view.spriteTransform.TranslateX = -558; 
     view.spriteTransform.TranslateY = 0; 
    } 
}