C# - 使用相同的名称文件替换当前用作背景的文件

时间:2017-10-11 12:16:00

标签: c# wpf image mvvm

我正在尝试创建一个按钮模板,我可以更改背景并用新的背景替换当前背景,这本身就可以了。但是我希望我作为背景放置的文件与发送它的按钮具有相同的名称,因此我需要删除/覆盖旧文件。 (这是为了在程序的下一次加载时它将再次找到图像)我得到文件的例外正在使用,这是合乎逻辑的,因为文件正在作为背景工作。我该如何解决这个问题?

我有一个Viewmodel,它包含imagelocation和它自己的名字,它在按下时会将新图像的名称设置为自身。

private void AddImage_Executed(object param)
    {
        //Normalized name of the sound
        var soundName = param as string;

        System.Windows.Forms.OpenFileDialog ofd = new System.Windows.Forms.OpenFileDialog();
        ofd.Filter = "All Graphics Types|*.jpg;*.gif;*.bmp;*.png;|All Files(*.*)|*.*";
        ofd.Multiselect = false;

        if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {
            //New file with the path to the selected file
            FileInfo imageFile = new FileInfo(ofd.FileName);
            //the new imageLocation with original extention but new name
            var newImageLocation = DefaultDirectory + soundName + imageFile.Extension;
            var oldImageLocation = DefaultDirectory + soundName + imageFile.Extension;
            //Check if the image with the same name as the sound exists and add it to the SoundViewModel
            var item = Sounds.FirstOrDefault(i => i.NormalizedName == soundName);
            if (item != null)
            {
                //If the item already has an image
                if(item.ImageLocation == newImageLocation)
                {
                    item.ImageLocation= null;
                    //Remove the file if it already exists
                    File.Delete(oldImageLocation);
                }

                //Move the file and rename it at the same time
                imageFile.CopyTo(newImageLocation, true);

                //Set the imagelocation to the new image
                item.ImageLocation = newImageLocation;
            } 
        }
    }

我在尝试删除文件之前更改了ImageLocation,但它似乎没有更新该信息,因此它仍然在按钮上显示图像。我该如何首先更新按钮图像?

这是我的按钮图像绑定的Xaml

<ImageBrush x:Key="ButtonImage" ImageSource="{Binding Path=ImageLocation}" Stretch="Uniform" Opacity="0.75"/>

0 个答案:

没有答案