【问题标题】:Why doesn't the SourceUpdated event trigger for my Image Control in WPF?为什么我的 WPF 中的图像控件没有触发 SourceUpdated 事件?
【发布时间】:2010-09-27 18:25:43
【问题描述】:

我的 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 事件。

谁能解释我做错了什么?

【问题讨论】:

  • protip:去掉废话,把所有东西都放在屏幕上,以增加有人回答你问题的可能性!

标签: c# wpf .net-3.5


【解决方案1】:

通过将值直接分配给 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)
{

}

【讨论】:

  • SetCurrentValue - 很好 - 我在进入 4.0 的新秀活动中没有意识到这一点...
  • 所以,我昨晚将我的项目升级到 4.0 并使用了 SetCurrentValue,但它仍然不会触发 SourceUpdated 事件。我删除了 XAML 文件中的所有绑定代码,并将控件的 SourceUpdated 事件指向正确的函数。我还缺少什么吗?
  • SourceUpdated 事件中的“Source”一词与图片来源无关,它指的是绑定的来源。如果控件更新绑定的源,将触发 SourceUpdated,而您的代码永远不会发生这种情况。但是应该触发 TargetUpdated 事件...
【解决方案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;
   }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-18
    • 2012-01-11
    • 1970-01-01
    • 2011-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多