在我們平時的開發中會經常用到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>
頂
Top
收藏
關注
評論