图像源未从第二次更新

时间:2015-03-12 05:40:12

标签: wpf image

我面临一个特殊的问题,当源从第二次开始修改时,图像不会更新。

我的xaml和代码背后。

 <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
            <RowDefinition Height="140"/>
        </Grid.RowDefinitions>
            <Grid  Grid.Row="2"  Margin="0 55 0 0" x:Name="ImageGrid"  >
            </Grid>
 </Grid>

FileSystemWatcher myWatcher;
Dispatcher myDisp;
private int count = 0;

public MainWindow()
{
        InitializeComponent();

        myWatcher = new FileSystemWatcher();
        myWatcher.Path = @"C:\Test";
        myWatcher.Filter = "hospital.png";
        myWatcher.NotifyFilter = NotifyFilters.LastWrite;
        myWatcher.Changed += myWatcher_Changed;
        myWatcher.EnableRaisingEvents = true;
        myDisp = Dispatcher.CurrentDispatcher;
}




void myWatcher_Changed(object sender, FileSystemEventArgs e)
        {
            myWatcher.EnableRaisingEvents = false;
            string aImgPath = @"C:\Test\hospital.png";
            if (File.Exists(aImgPath))
            {
                BitmapImage src = new BitmapImage();
                src.BeginInit();
                src.UriSource = new Uri(aImgPath, UriKind.Relative);
                src.CacheOption = BitmapCacheOption.OnLoad;
                src.EndInit();
                src.Freeze();
                myDisp.Invoke(DispatcherPriority.Normal, new Action<BitmapImage>(UpdateImage), src);
            }
            myWatcher.EnableRaisingEvents = true;
        }

 void UpdateImage(BitmapImage theImage)
        {
            ImageGrid.Children.Clear();
            Image aImg = new Image();
            aImg.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
            aImg.VerticalAlignment = System.Windows.VerticalAlignment.Top;
            aImg.Height = 70;
            aImg.Width = 250;
            aImg.Stretch = Stretch.Uniform;
            aImg.Source = theImage;
            ImageGrid.Children.Add(aImg);
        }

当文件hospital.png更新时,此代码将被执行;但是UI仍然会从第二次开始显示旧图像。我做错了什么?

1 个答案:

答案 0 :(得分:0)

问题是WPF缓存了映像文件Uri。因为它永远不会改变,所以不会加载新图像。

然而,您可以从FileStream加载图像:

if (File.Exists(aImgPath))
{
    var src = new BitmapImage();
    using (var fs = new FileStream(
        aImgPath, FileMode.Open, FileAccess.Read, FileShare.Read))
    {
        src.BeginInit();
        src.StreamSource = fs;
        src.CacheOption = BitmapCacheOption.OnLoad;
        src.EndInit();
    }
    src.Freeze();
    myDisp.Invoke(DispatcherPriority.Normal, new Action<BitmapImage>(UpdateImage), src);
}