用WPF中的依賴屬性做一個展示隨機圖片的功能
阿新 • • 發佈:2022-04-18
首先寫一個類用於隨機返回資料夾中的圖片全路徑
internal class GetImageClass { public static string GetFilesWithRandom(DirectoryInfo dir) { FileSystemInfo[] fileinfo = dir.GetFileSystemInfos(); //初始化一個FileSystemInfo型別的例項 Random random = new Random(); //生成隨機數 int dirNum = random.Next(0, fileinfo.Length - 1); if (fileinfo[dirNum] is DirectoryInfo) { GetFilesWithRandom(fileinfo[dirNum] as DirectoryInfo); //如果選到了子資料夾,則進行遞迴查詢 } else { if(fileinfo[dirNum].FullName.Substring(fileinfo[dirNum].FullName.Length-3).ToLower()=="jap") { if(fileinfo.Length==1) { return null; } GetFilesWithRandom(dir); } return fileinfo[dirNum].FullName; }return null; } }
定義一個類,讓它繼承DependencyObject類,用來儲存返回的圖片路徑
public class FIleData:DependencyObject { public string MyProperty { get { return (string)GetValue(MyPropertyProperty); } set { SetValue(MyPropertyProperty, value); } } // Using a DependencyProperty as the backing store for MyProperty. This enables animation, styling, binding, etc... public static readonly DependencyProperty MyPropertyProperty = DependencyProperty.Register("MyProperty", typeof(string), typeof(FIleData)); }
該窗體的後臺程式碼,其中DispatcherTimer 類用於每過一秒改變依賴屬性MyProperty的值,來達到自動切換圖片的功能
public partial class MainWindow : Window { private DispatcherTimer timer; FIleData fIleData = new FIleData(); public MainWindow() { InitializeComponent(); this.DataContext= fIleData; //設定該窗體的上下文 initRect(); } private void initRect() { double x1 = SystemParameters.PrimaryScreenWidth;//得到螢幕整體寬度 double y1 = SystemParameters.PrimaryScreenHeight;//得到螢幕整體高度 this.Width = x1; this.Height = y1; this.WindowStartupLocation =WindowStartupLocation.CenterScreen; timer = new DispatcherTimer(); timer.Interval = TimeSpan.FromSeconds(1); timer.Tick += timer1_Tick; timer.Start(); } private void timer1_Tick(object sender, EventArgs e) { //(你的定時處理) DirectoryInfo dir = new DirectoryInfo("C:\\Users\\zm962\\Pictures\\新建資料夾"); fIleData.MyProperty = GetImageClass.GetFilesWithRandom(dir); } }
最後在前臺繫結依賴屬性MyProperty即可,每過一秒,會隨機返回一個新的路徑,介面也隨之切換