2010-09-27 371 views
3

我有一个窗口的图像控制在我的WPF项目为什么SourceUpdated事件不会触发我在WPF中的图像控件?

XAML:

<Image 
    Source="{Binding NotifyOnSourceUpdated=True, NotifyOnTargetUpdated=True}" 
    Binding.SourceUpdated="bgMovie_SourceUpdated" 
    Binding.TargetUpdated="bgMovie_TargetUpdated" /> 

在代码中,我改变了图像的源

C#:

myImage = new BitmapImage(); 
myImage.BeginInit(); 
myImage.UriSource = new Uri(path); 
myImage.EndInit(); 
this.bgMovie.Source = myImage; 

但是bgMovie_SourceUpdated事件永远不会被触发。

任何人都可以阐明我做错了什么?

+3

普罗蒂普:切出的废话,适合在屏幕上的一切,以提高回答你的问题的人的可能性! – Will 2010-09-27 18:48:34

回答

6

通过直接assiging一个值Source财产,你是 “解除绑定” 吧...你Image控制不再被数据绑定,它只是具有本地价值。

在4.0中,您可以使用SetCurrentValue方法:

this.bgMovie.SetCurrentValue(Image.SourceProperty, myImage); 

不幸的是这个方法不可用在3.5,并没有很不错的选择......

不管怎么说,你有什么想做到了吗?如果你手动设置它,绑定Source属性有什么意义?如果要检测什么时候Source属性发生变化,您可以使用DependencyPropertyDescriptor.AddValueChanged方法:

var prop = DependencyPropertyDescriptor.FromProperty(Image.SourceProperty, typeof(Image)); 
prop.AddValueChanged(this.bgMovie, SourceChangedHandler); 
... 

void SourceChangedHandler(object sender, EventArgs e) 
{ 

} 
+0

SetCurrentValue - nice - 我没有意识到这一点,在我的菜鸟运动到4.0 ... – 2010-09-27 19:02:31

+0

因此,我昨晚升级了我的项目到4.0,并使用SetCurrentValue,但它仍然不会触发SourceUpdated事件。我删除了XAML文件中的所有绑定代码,并将控件的SourceUpdated事件指向了正确的函数。我还错过了什么吗? – 2010-09-28 11:50:12

+0

SourceUpdated事件中的“源”字与图像源无关,它指的是绑定的来源。如果控件更新了绑定的来源,则SourceUpdated将被触发,而您的代码永远不会发生这种情况。但是应该触发TargetUpdated事件... – 2010-09-28 13:43:44

2

通过在代码中对源代码进行硬编码,您打破了XAML中的绑定。

而不是这样做,绑定到您使用(大部分)与上面相同的代码设置的属性。这是一种方法。

XAML:

<Image Name="bgMovie" 
     Source="{Binding MovieImageSource, 
         NotifyOnSourceUpdated=True, 
         NotifyOnTargetUpdated=True}" 
     Binding.SourceUpdated="bgMovie_SourceUpdated" 
     Binding.TargetUpdated="bgMovie_TargetUpdated" /> 

C#:

public ImageSource MovieImageSource 
    { 
     get { return mMovieImageSource; } 
     // Set property sets the property and implements INotifyPropertyChanged 
     set { SetProperty("MovieImageSource", ref mMovieImageSource, value); } 
    } 

    void SetMovieSource(string path) 
    { 
     myImage = new BitmapImage(); 
     myImage.BeginInit(); 
     myImage.UriSource = new Uri(path); 
     myImage.EndInit(); 
     this.MovieImageSource = myImage; 
    } 
相关问题