WPF中视图(图像标签中的Source属性)中的属性更改时如何更改属性?

问题描述 投票:0回答:1

我有一张图像,我希望在用户更改图像来源时收到通知。因此,当用户更改图像时,它应该在视图模型中自动更改。

此代码是我的图像源发生变化的地方。

OpenFileDialog fileDialog = new OpenFileDialog();
if (fileDialog.ShowDialog() == true)
{
        Image.Source = new BitmapImage(new Uri(fileDialog.FileName)); //here I want to 
         //change the imagePath in my view model too.
        isImageChanged = true;
}

xaml代码

<Image Width="50"
       Name = "Image"
       Height="50"
       Source="{Binding ImagePath,UpdateSourceTrigger=PropertyChanged},Converter={StaticResource StringToPathConverter}">
            
</Image>

查看模型

private string _imagePath;
public string ImagePath
{
   get
   {
     return _imagePath;
   }
   set
   {
       _imagePath = value;
       OnPropertyChanged(nameof(ImagePath));
   }
}

这是转换器代码

public class StringToPathConverter:IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            string res = AppDomain.CurrentDomain.BaseDirectory.ToString() + "images\\" + value;
            return res;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            string res = value.ToString().Split(':')[1];
            return res;
        }
    }

我在 imagePath 集上设置了断点,但它不起作用。我不知道是否可以通过绑定来做到这一点,如果是或不是如何?

c# wpf mvvm binding
1个回答
2
投票

Image.Source
属性的绑定默认为
OneWay

您必须将其声明为

TwoWay
:

<Image Source="{Binding ImagePath,
                Mode=TwoWay,
                Converter={StaticResource StringToPathConverter}}"/>

请注意,这需要

ConvertBack
StringToPathConverter
方法的有效实现,该方法必须从
ImageSource
转换为路径字符串。

您应该避免这种情况,而是直接更改源属性:

if (fileDialog.ShowDialog() == true)
{
    viewModel.ImagePath = fileDialog.FileName;
}
© www.soinside.com 2019 - 2024. All rights reserved.