DataBinding and Timer in WPF?
I'm gonna write a code with DataBinding and a Timer to change an Image sequentially.
e.g: in each two seconds.below is my C# code :
public class GenerateRandomImagePath
{
Random random = new Random((int)DateTime.Now.Ticks);
readonly int MinInt;
readonly int MaxInt;
readonly string PrefixImagesName;
readonly string ImageExtension;
/// <summary>
/// Used in data binding
/// </summary>
public string ImageFullPath { get; set; }
public GenerateRandomImagePath(string prefixName, string extension)
{
this.PrefixImagesName = prefixName;
this.MinInt = 1;
this.MaxInt = 100;
this.ImageExtension = extension;
}
int RandomNumber()
{
return random.Next(this.MinInt, this.MaxInt);
}
public void GenerateNewRandomImagePath()
{
this.ImageFullPath = this.PrefixImagesName + RandomNumber() + this.ImageExtension;
}
}
public partial class MainWindow : Window
{
GenerateRandomImagePath RandomImagePath;
System.Timers.Timer timer = new System.Timers.Timer(2000);
public MainWindow()
{
InitializeComponent();
RandomImagePath = new GenerateRandomImagePath(@"C:\Users\MDS\Pictures\Nature 02\Nature ", @".jpg");
timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
timer.Enabled = 开发者_JS百科true;
this.DataContext = RandomImagePath;
RandomImagePath.GenerateNewRandomImagePath();//this line works well
}
void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
RandomImagePath.GenerateNewRandomImagePath();
}
}
The XAML code :
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
x:Class="sth.MainWindow"
x:Name="Window"
Title="MainWindow"
Width="800" Height="600" mc:Ignorable="d">
<Grid x:Name="LayoutRoot">
<Image Source="{Binding Path=ImageFullPath}" />
</Grid>
</Window>
The code works just for first time! After that, the timer changes ImageSource but it doesn't effect on view!
Would you please guide me?Thanks
According to your code, the GenerateRandomImagePath class doesn't implement INotifyPropertyChanged. WPF can't know that the ImageFullPath has changed unless you tell it, either by implementing that interface or by changing the class to derive from DependencyObject and turning the property into a dependency property.
I would suggest implementing INotifyPropertyChanged - it's a more lightweight approach.
public class GenerateRandomImagePath : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName);
}
private string _imageFullPath;
public string ImageFullPath
{
get { return _imageFullPath; }
set
{
_imageFullPath = value;
OnPropertyChanged("ImageFullPath");
}
}
}
精彩评论