Dependency Properties that use the property afterwards?
我正在尝试设置一个名为 Sprite 的对象的依赖属性,一个 sprite 包含一个 spriteSheet 字符串,所以我希望能够传递一个 Sprite,然后该数据用于显示一个图像在我的控制中。
这是我目前的尝试
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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 方法的那部分运行,正如我在依赖属性文档中读到的那样,绑定时可能会直接调用 SetValue 和 GetValue。
添加一个 DependencyPropertyChangedEventHandler 并将代码从您的设置器移到那里:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | 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; } } |
没错,你不能用 SetValue 来引入任何逻辑。相反,您应该使用 PropertyValueChanged 处理程序。类似于:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | 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)); |