我正在尝试设置一个依赖属性,该属性是一个名为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" }));
}
如何运行set方法的那一部分,因为我在Dependency Property文档中读到了绑定时可能直接调用SetValue和GetValue。
答案 0 :(得分: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));
答案 1 :(得分:3)
添加DependencyPropertyChangedEventHandler并从那里移动你的setter中的代码:
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;
}
}