WPF Image控件的绑定

      在我们平时的开发中会经常用到Image控件,通过设置Image控件的Source属性,我们可以加载图片,设置Image的source属性时可以使用相对路径也可以使用绝对路径,一般情况下建议使用绝对路径,类似于下面的形式Source="/Demo;Component/Images/Test.jpg"其中Demo表示工程的名称,后面表示具体哪个文件夹下面的哪个图片资源,在程序中,我们甚至可以为Image控件设置X:Name属性,在后台代码中动态去改变Image的Source,但我个人认为这种方式不太适合最大量的图片切换,而且增加了View层和代码之间的耦合性,不是和复合MVVM的核心设计思想,所以今天就总结一下Image的动态绑定的形式。

    要绑定,肯定是绑定到Image控件的Source属性上面,我们首先要搞清楚Source的类型是什么,public ImageSource Source { get; set; }也就是ImageSource类型,当然在我们绑定的时候用的最多的就是BitmapImage这个位图图像啦,我们首先来看看BitmapImage的继承关系:BitmapImage:BitmapSource:ImageSource,最终也是一种ImageSource类型。当然在我们的Model层中我们也可以直接定义一个BitmapImage的属性,然后将这个属性直接绑定到Image的Source上面,当然这篇文章我们定义了一个ImgSource的String类型,所以必须要定义一个转换器Converter,这里分别贴出相应地代码。

Model

public class ImgInfo : NotifyPropertyChanged
    {
        private string imgPath;

        public string ImgPath
        {
            get { return imgPath; }
            set { imgPath = value; OnPropertyChanged(() => this.ImgPath); }
        }
        private int index;

        public int Index
        {
            get { return index; }
            set
            {

                if (value >= 0 && value < Paths.Count)
                {
                    index = value;
                    ImgPath = Paths[value];
                }
            }
        }

        public List<string> Paths { get; set; } = new List<string>();
    }
    public abstract class NotifyPropertyChanged : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged<T>(Expression<Func<T>> expression)
        {
            if (PropertyChanged != null)
            {
                PropertyChangedEventArgs e = new PropertyChangedEventArgs(((MemberExpression)expression.Body).Member.Name);
                PropertyChanged(this, e);
            }
        }

        public virtual void RaisePropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler propertyChanged = PropertyChanged;
            if (propertyChanged != null)
            {
                PropertyChangedEventArgs e = new PropertyChangedEventArgs(propertyName);
                propertyChanged(this, e);
            }
        }

        public virtual void OnPropertyChanged(string propertyName)
        {
            this.RaisePropertyChanged(propertyName);
        }
    }

后台数据:

  public MainWindow()
        {
            InitializeComponent();

            imgInfo = new ImgInfo();
            imgInfo.Paths = Directory.GetFiles("imgs","*.jpg").ToList();
            // imgInfo.Paths =Directory.GetFiles("imgs").Select(t=>$"WpfApp1;Component/{t}").ToList();
            imgInfo.Index = 0;
            this.DataContext = imgInfo;
        }

然后就是重要的转换器:

 public class StringToImageSourceConverter : IValueConverter
    {
        #region Converter

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            string path = (string)value;
            if (!string.IsNullOrEmpty(path))
            {
                return new BitmapImage(new Uri(path, UriKind.Relative));
            }
            else
            {
                return null;
            }

        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return null;
        }
        #endregion

    }

  xaml

  <Window.Resources>
        <local:StringToImageSourceConverter x:Key="sti"/>
    </Window.Resources>

   <Grid >
          <Grid.Background>
                <ImageBrush ImageSource="{Binding     
                        Path=ImgPath,Converter={StaticResource sti}}"/>

            </Grid.Background>

 

posted @ 2019-10-22 21:13  幕三少  阅读(1320)  评论(0编辑  收藏  举报