我的WPF项目中的窗口上有一个图像控件
XAML:
<Image
Source="{Binding NotifyOnSourceUpdated=True, NotifyOnTargetUpdated=True}"
Binding.SourceUpdated="bgMovie_SourceUpdated"
Binding.TargetUpdated="bgMovie_TargetUpdated" />
Run Code Online (Sandbox Code Playgroud)
在代码中,我正在改变图像的来源
C#:
myImage = new BitmapImage();
myImage.BeginInit();
myImage.UriSource = new Uri(path);
myImage.EndInit();
this.bgMovie.Source = myImage;
Run Code Online (Sandbox Code Playgroud)
但是从不触发bgMovie_SourceUpdated事件.
有人能说清楚我做错了吗?
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);
Run Code Online (Sandbox Code Playgroud)
不幸的是,这种方法在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)
{
}
Run Code Online (Sandbox Code Playgroud)
通过在代码中对源进行硬编码,您将破坏 XAML 中的绑定。
不要这样做,而是绑定到您使用(大部分)上面相同的代码设置的属性。这是一种方法。
XAML:
<Image Name="bgMovie"
Source="{Binding MovieImageSource,
NotifyOnSourceUpdated=True,
NotifyOnTargetUpdated=True}"
Binding.SourceUpdated="bgMovie_SourceUpdated"
Binding.TargetUpdated="bgMovie_TargetUpdated" />
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)