开发环境建议使用VS2010及以上
效果:
xaml代码:
- <Window
- xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
- xmlns:Microsoft_Windows_Themes="clr-namespace:Microsoft.Windows.Themes;assembly=PresentationFramework.Aero" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:PictureTest" xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity" xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions" mc:Ignorable="d"
- x:Class="PictureTest.MainWindow"
- x:Name="Window"
- Title="MainWindow"
- Width="640" Height="480">
- <Grid x:Name="LayoutRoot">
- <Image Name="image1" Height="429" HorizontalAlignment="Left" Margin="96,10,0,0" Source="{Binding Path=ImageFullPath}" Stretch="Fill" VerticalAlignment="Top" Width="302" />
- </Grid>
- </Window>
C#代码(后端代码)
- using System;
- using System.Windows;
- using System.ComponentModel;
-
- namespace PictureTest
- {
- /// <summary>
- /// MainWindow.xaml 的交互逻辑
- /// </summary>
- public class GenerateRandomImagepath : INotifyPropertyChanged
- {
- public event PropertyChangedEventHandler PropertyChanged;
-
- private void OnPropertyChanged(string propertyName)
- {
- if (PropertyChanged != null)
- PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
- }
-
- private string _imageFullPath;
-
- Random random = new Random((int)DateTime.Now.Ticks);
- readonly int Minint;
- readonly int Maxint;
- readonly string PrefixImageName;
- readonly string ImageExtension;
- /// <summary>
- /// Used in data Binding
- /// </summary>
- public string ImageFullPath { get{return _imageFullPath;}
- set
- {
- _imageFullPath = value;
- OnPropertyChanged("ImageFullPath");
- }
- }
-
- public GenerateRandomImagepath(string prefixName, string extension)
- {
- this.PrefixImageName = prefixName;
- this.Minint = 1;
- this.Maxint = 6;
- this.ImageExtension = extension;
- }
-
- int RandomNumber()
- {
- return random.Next(this.Minint, this.Maxint);
- }
-
- public void GenerateNewRandomImagePath()
- {
- this.ImageFullPath = this.PrefixImageName + RandomNumber() + this.ImageExtension;
- }
-
- }
-
- public partial class MainWindow : Window
- {
- GenerateRandomImagepath RandomImagePath;
- System.Timers.Timer timer = new System.Timers.Timer(2000);
-
- public MainWindow()
- {
- this.InitializeComponent();
-
- // 在此点下面插入创建对象所需的代码。
- RandomImagePath = new GenerateRandomImagepath(@"C:\Users\Administrator\Documents\Expression\Blend 4\Projects\PictureTest\PictureTest\Image\", @".jpg");
- timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
- timer.Enabled = true;
- //timer.Start();
-
- this.DataContext = RandomImagePath;
- RandomImagePath.GenerateNewRandomImagePath();
- }
- void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
- {
- RandomImagePath.GenerateNewRandomImagePath();
- }
- }
- }