如何在c#中使用图像控件

  介绍

这篇文章给大家介绍如何在c#中使用图像控件,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

首先是视图层,比较简单:

& lt; Grid  Grid.Row=?“比;   ,,,,,& lt; Image 源=皗Binding 路径=LTEModel.ImgSource转换器={StaticResource  MyImageConverter}}“,拉伸=癋ill"比;   ,,,,,& lt;/Image>   ,,,& lt;/Grid>

然后我们再来看看模型层也很简单。

public  class  LTEModel : BaseModel   {才能   ,,,private  string  _imageSource =,空;   ,,,public  string  ImgSource   ,,,{   ,,,,,   ,,,,,{   ,,,,,,,return  _imageSource;   ,,,,,}   ,,,,,   ,,,,,{   ,,,,,,,if  (value  !=, _imageSource)   ,,,,,,,{   ,,,,,,,,,=,_imageSource 价值;   ,,,,,,,,,FirePropertyChanged (“ImgSource");   ,,,,,,,}   ,,,,,}   ,,,}   以前,,}

然后就是重要的转换器:

public  class  StringToImageSourceConverter: IValueConverter   {才能   ,,# region 转换器      ,,,public  object 转换(object 价值,Type  targetType,, object 参数,,CultureInfo 文化)   ,,,{   ,,,,,string  path =, (string)值;   ,,,,,if  (! string.IsNullOrEmpty(路径))   ,,,,,{   ,,,,,,,return  new  BitmapImage (new  Uri(路径,UriKind.Absolute));   ,,,,,}   ,,,,,   ,,,,,{   ,,,,,,,return 零;   ,,,,,}   ,,,}      ,,,public  object  ConvertBack (object 价值,Type  targetType,, object 参数,,CultureInfo 文化)   ,,,{   ,,,,,return 零;   ,,,}   ,,,# endregion   以前,,}

然后就是重要的转换器:

public  class  StringToImageSourceConverter: IValueConverter   {才能   ,,# region 转换器      ,,,public  object 转换(object 价值,Type  targetType,, object 参数,,CultureInfo 文化)   ,,,{   ,,,,,string  path =, (string)值;   ,,,,,if  (! string.IsNullOrEmpty(路径))   ,,,,,{   ,,,,,,,return  new  BitmapImage (new  Uri(路径,UriKind.Absolute));   ,,,,,}   ,,,,,   ,,,,,{   ,,,,,,,return 零;   ,,,,,}   ,,,}      ,,,public  object  ConvertBack (object 价值,Type  targetType,, object 参数,,CultureInfo 文化)   ,,,{   ,,,,,return 零;   ,,,}   ,,,# endregion   以前,,}

转换器返回的是对象类型,实际返回的是一个BitmapImage对象,所以我们在写程序绑定的时候一定要弄清绑定的目标和对象之间的关系,这个是非常重要的。

下面就是在ViewModel层中来添加绑定,并更新数据源,这里使用的是一个定时器来定时更新数据源:

public  class  LTEViewModel : NotifyObject   {才能   ,,,private  DispatcherTimer  myDispatcher =,空;   ,,,private  Random  Random =, new 随机();   ,,,public  LTEViewModel ()   ,,,{   ,,,,,GetImageSource ();   ,,,,,InitTimer ();   ,,,}      ,,,private  LTEModel  _lteModel =,空;   ,,,public  LTEModel  LTEModel   ,,,{   ,,,,,   ,,,,,{   ,,,,,,,if  (_lteModel ==, null)   ,,,,,,,{   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null

如何在c#中使用图像控件