Why doesn't the SourceUpdated event trigger for my Image Control in WPF?
I have an image control on a Window in my WPF project
XAML:
<Image 
  Source="{Binding NotifyOnSourceUpdated=True, Notif开发者_开发知识库yOnTargetUpdated=True}" 
  Binding.SourceUpdated="bgMovie_SourceUpdated" 
  Binding.TargetUpdated="bgMovie_TargetUpdated" />
In code I am changing the source of the image
C#:
myImage = new BitmapImage();
myImage.BeginInit();
myImage.UriSource = new Uri(path);
myImage.EndInit();
this.bgMovie.Source = myImage;
But the bgMovie_SourceUpdated event is never triggered.
Can anyone shed some light on what I'm doing wrong?
By assiging a value directly to the Source property, you're "unbinding" it... Your Image control is not databound anymore, it just has a local value.
In 4.0 you could use the SetCurrentValue method:
this.bgMovie.SetCurrentValue(Image.SourceProperty, myImage);
Unfortunately this method isn't available in 3.5, and there is no easy alternative...
Anyway, what are you trying to do exactly ? What is the point of binding the Source property if you're setting it manually anyway ? If you want to detect when the Source property changes, you can use the DependencyPropertyDescriptor.AddValueChanged method:
var prop = DependencyPropertyDescriptor.FromProperty(Image.SourceProperty, typeof(Image));
prop.AddValueChanged(this.bgMovie, SourceChangedHandler);
...
void SourceChangedHandler(object sender, EventArgs e)
{
}
By hard-coding the Source in the code, you are breaking the Binding in your XAML.
Instead of doing that, bind to a property that you set using (most of) the same code above. Here's one way to do that.
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;
   }
 
         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论