C# WPF Image控件的綁定方法
在我們平時(shí)的開發(fā)中會(huì)經(jīng)常用到Image控件,通過設(shè)置Image控件的Source屬性,我們可以加載圖片,設(shè)置Image的source屬性時(shí)可以使用相對(duì)路徑也可以使用絕對(duì)路徑,一般情況下建議使用絕對(duì)路徑,類似于下面的形式Source="/Demo;Component/Images/Test.jpg"其中Demo表示工程的名稱,后面表示具體哪個(gè)文件夾下面的哪個(gè)圖片資源,在程序中,我們甚至可以為Image控件設(shè)置X:Name屬性,在后臺(tái)代碼中動(dòng)態(tài)去改變Image的Source,但我個(gè)人認(rèn)為這種方式不太適合最大量的圖片切換,而且增加了View層和代碼之間的耦合性,不是和復(fù)合MVVM的核心設(shè)計(jì)思想,所以今天就總結(jié)一下Image的動(dòng)態(tài)綁定的形式。
要綁定,肯定是綁定到Image控件的Source屬性上面,我們首先要搞清楚Source的類型是什么,public ImageSource Source { get; set; }也就是ImageSource類型,當(dāng)然在我們綁定的時(shí)候用的最多的就是BitmapImage這個(gè)位圖圖像啦,我們首先來看看BitmapImage的繼承關(guān)系:BitmapImage:BitmapSource:ImageSource,最終也是一種ImageSource類型。當(dāng)然在我們的Model層中我們也可以直接定義一個(gè)BitmapImage的屬性,然后將這個(gè)屬性直接綁定到Image的Source上面,當(dāng)然這篇文章我們定義了一個(gè)ImgSource的String類型,所以必須要定義一個(gè)轉(zhuǎn)換器Converter,這里分別貼出相應(yīng)地代碼。
首先是View層,比較簡(jiǎn)單:
<Grid Grid.Row="1">
<Image Source="{Binding Path=LTEModel.ImgSource,Converter={StaticResource MyImageConverter}}" Stretch="Fill">
</Image>
</Grid>
然后我們?cè)賮砜纯碝odel層也很簡(jiǎn)單。
public class LTEModel : BaseModel
{
private string _imageSource = null;
public string ImgSource
{
get
{
return _imageSource;
}
set
{
if (value != _imageSource)
{
_imageSource = value;
FirePropertyChanged("ImgSource");
}
}
}
}
然后就是重要的轉(zhuǎn)換器:
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.Absolute));
}
else
{
return null;
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return null;
}
#endregion
}
然后就是重要的轉(zhuǎn)換器:
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.Absolute));
}
else
{
return null;
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return null;
}
#endregion
}
轉(zhuǎn)換器返回的是Object類型,實(shí)際返回的是一個(gè)BitmapImage對(duì)象。所以我們?cè)趯懗绦蚪壎ǖ臅r(shí)候一定要弄清綁定的目標(biāo)和對(duì)象之間的關(guān)系,這個(gè)是非常重要的。
下面就是在ViewModel層中來添加綁定,并更新數(shù)據(jù)源,這里使用的是一個(gè)定時(shí)器來定時(shí)更新數(shù)據(jù)源:
public class LTEViewModel : NotifyObject
{
private DispatcherTimer myDispatcher = null;
private Random random = new Random();
public LTEViewModel()
{
GetImageSource();
InitTimer();
}
private LTEModel _lteModel = null;
public LTEModel LTEModel
{
get
{
if (_lteModel == null)
{
_lteModel = new LTEModel();
}
return _lteModel;
}
set
{
if (value != _lteModel)
{
_lteModel = value;
FirePropertyChanged("LTEModel");
}
}
}
private BaseModel _baseModel = null;
public BaseModel BaseModelInstance
{
get
{
if (_baseModel == null)
{
_baseModel = new BaseModel()
{
Title = "分地區(qū)LTE分布",
Time = DateTime.Now.ToString()
};
}
return _baseModel;
}
set
{
if (value != _baseModel)
{
_baseModel = value;
FirePropertyChanged("BaseModelInstance");
}
}
}
private List<string> imgList = new List<string>();
private void GetImageSource()
{
//通過程序集來讀取相應(yīng)的資源的路徑
string assemblyLocation = this.GetType().Assembly.Location;
string assLocation = assemblyLocation.Substring(0, assemblyLocation.LastIndexOf("\\"));
string[] img_files = Directory.GetFiles(string.Format("{0}\\Images", assLocation), "*.JPG");
foreach (string img_path in img_files)
{
imgList.Add(img_path);
}
}
private void InitTimer()
{
myDispatcher = new DispatcherTimer();
myDispatcher.Tick += new EventHandler(Timer_Tick);
myDispatcher.Interval = TimeSpan.FromMilliseconds(1000);
myDispatcher.Start();
}
private void Timer_Tick(object sender, EventArgs e)
{
int imageIndex = 0;
if (imgList.Count > 0 && LTEModel != null)
{
imageIndex = random.Next(0, imgList.Count);
LTEModel.ImgSource = imgList[imageIndex];
}
if (_baseModel != null)
{
_baseModel.Time = DateTime.Now.ToString();
}
}
}
然后就是實(shí)例化一個(gè)ViewModel對(duì)象綁定到前臺(tái)中,這個(gè)思路其實(shí)是相當(dāng)明確的。
其實(shí)在我們的很多時(shí)候,我們并不知道我們需要綁定什么圖片,或者說根據(jù)數(shù)據(jù)類型來綁定圖片,這個(gè)在定義數(shù)據(jù)模板的時(shí)候經(jīng)常使用到,下面就介紹一下,根據(jù)類型來綁定相應(yīng)的圖片。然后通過定義
public enum DeviceType
{
SheXiangJi,
KaKou,
DianZiJingCha,
MingJin
}
這種類型,通過不同的類型來綁定到不同的圖片,這個(gè)也是一個(gè)非常重要的應(yīng)用,我們一定要注意使用的方法,這里只是簡(jiǎn)單介紹一下。
<ItemsControl ItemsSource="{Binding DeviceList,RelativeSource={RelativeSource TemplatedParent}}" Grid.Row="2">
<ItemsControl.Template>
<ControlTemplate TargetType="ItemsControl">
<UniformGrid Columns="3" Rows="7" IsItemsHost="True"></UniformGrid>
</ControlTemplate>
</ItemsControl.Template>
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Left" Margin="20 0 0 0" VerticalAlignment="Center" SnapsToDevicePixels="True">
<Image x:Name="icon1" Width="48" Height="48" RenderOptions.BitmapScalingMode="NearestNeighbor" VerticalAlignment="Center"></Image>
<TextBlock Margin="10 0 0 0" Foreground="#fff" ToolTip="{Binding Name}" FontSize="40" Text="{Binding Name}" HorizontalAlignment="Left" VerticalAlignment="Center"></TextBlock>
</StackPanel>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding Type}" Value="SheXiangJi">
<Setter Property="Source" Value="/IGisControls.JTJ.UIControls;component/images/camera.png" TargetName="icon1"></Setter>
</DataTrigger>
<DataTrigger Binding="{Binding Type}" Value="KaKou">
<Setter Property="Source" Value="/IGisControls.JTJ.UIControls;component/images/Bayonet.png" TargetName="icon1"></Setter>
</DataTrigger>
<DataTrigger Binding="{Binding Type}" Value="DianZiJingCha">
<Setter Property="Source" Value="/IGisControls.JTJ.UIControls;component/images/epolice.png" TargetName="icon1"></Setter>
</DataTrigger>
<DataTrigger Binding="{Binding Type}" Value="MingJin">
<Setter Property="Source" Value="/IGisControls.JTJ.UIControls;component/images/Police_A.png" TargetName="icon1"></Setter>
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
另外和Image很類似的就是 <ImageBrush ImageSource="/IGisControls.JTJ.UIControls;component/images/screenBG.jpg" Stretch="Fill"></ImageBrush>
用法也差不多,同樣可以通過綁定的方式來添加圖片,不過在使用的時(shí)候還是需要注意一下就是設(shè)置當(dāng)前圖片的生成操作為Resource。
以上就是C# WPF Image控件的綁定方法的詳細(xì)內(nèi)容,更多關(guān)于C# WPF Image控件的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
C# BackgroundWorker組件學(xué)習(xí)入門介紹
一個(gè)程序中需要進(jìn)行大量的運(yùn)算,并且需要在運(yùn)算過程中支持用戶一定的交互,為了獲得更好的用戶體驗(yàn),使用BackgroundWorker來完成這一功能2013-10-10
C#關(guān)于Textbox滾動(dòng)顯示最后一行,不閃爍問題
這篇文章主要介紹了C#關(guān)于Textbox滾動(dòng)顯示最后一行,不閃爍問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-04-04
在Winform和WPF中注冊(cè)全局快捷鍵實(shí)現(xiàn)思路及代碼
如果注冊(cè)快捷鍵,RegisterHotKey中的fsModifiers參數(shù)為0,即None選項(xiàng),一些安全軟件會(huì)警報(bào),可能因?yàn)檫@樣就可以全局監(jiān)聽鍵盤而造成安全問題,感興趣的你可以參考下本文2013-02-02
Visual Studio連接unity編輯器的實(shí)現(xiàn)步驟
unity編輯器中打開C#腳本的時(shí)候發(fā)現(xiàn)Visual Studio沒有連接unity編輯器,本文主要介紹了Visual Studio連接unity編輯器的實(shí)現(xiàn)步驟,感興趣的可以了解一下2023-11-11
C#實(shí)現(xiàn)利用Windows API讀寫INI文件的方法
這篇文章主要介紹了C#實(shí)現(xiàn)利用Windows API讀寫INI文件的方法,涉及C#針對(duì)ini文件的創(chuàng)建、讀取及寫入等操作技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-07-07

