在咱們平時的開發中會常常用到Image控件,經過設置Image控件的Source屬性,咱們能夠加載圖片,設置Image的source屬性時可使用相對路徑也可使用絕對路徑,通常狀況下建議使用絕對路徑,相似於下面的形式Source="/Demo;Component/Images/Test.jpg"其中Demo表示工程的名稱,後面表示具體哪一個文件夾下面的哪一個圖片資源,在程序中,咱們甚至能夠爲Image控件設置X:Name屬性,在後臺代碼中動態去改變Image的Source,但我我的認爲這種方式不太適合最大量的圖片切換,並且增長了View層和代碼之間的耦合性,不是和複合MVVM的核心設計思想,因此今天就總結一下Image的動態綁定的形式。express
要綁定,確定是綁定到Image控件的Source屬性上面,咱們首先要搞清楚Source的類型是什麼,public ImageSource Source { get; set; }也就是ImageSource類型,固然在咱們綁定的時候用的最多的就是BitmapImage這個位圖圖像啦,咱們首先來看看BitmapImage的繼承關係:BitmapImage:BitmapSource:ImageSource,最終也是一種ImageSource類型。固然在咱們的Model層中咱們也能夠直接定義一個BitmapImage的屬性,而後將這個屬性直接綁定到Image的Source上面,固然這篇文章咱們定義了一個ImgSource的String類型,因此必需要定義一個轉換器Converter,這裏分別貼出相應地代碼。this
Modelspa
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; }
而後就是重要的轉換器:code
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 }
xamlblog
<Window.Resources> <local:StringToImageSourceConverter x:Key="sti"/> </Window.Resources> <Grid > <Grid.Background> <ImageBrush ImageSource="{Binding Path=ImgPath,Converter={StaticResource sti}}"/> </Grid.Background>