我當前的實作回圈遍歷檔案夾中的 PNG 檔案,并從該檔案夾中的檔案中創建許多帶有背景影像的按鈕。
為此,在 Visual Studio 的設計時,我必須將該檔案夾中每個 PNG 的構建操作設定為resource
,然后使用以下內容
button.Content = new Image {
Source = new BitmapImage(new Uri(product.ImageLink ?? "",UriKind.Relative)),
Stretch = Stretch.Fill
}
這種方法的問題在于,每次將新的 PNG 檔案添加到檔案夾時,我都需要將該 PNG 檔案的構建操作設定為resource
并重新發布解決方案。
是否可以在運行時遍歷檔案夾中的所有 PNG 檔案以將它們用作按鈕內容?
uj5u.com熱心網友回復:
只需列舉檔案夾并將感興趣的檔案路徑添加到 a List
orObservableCollection
并將其系結到 a ListBox
(或任何ItemsControl
選擇)。定義 aDataTemplate
以呈現影像按鈕。您可以使用FileSystemWatcher
來觀察目錄的變化。
主視窗.xaml.cs
public partial class MainWindow : Window
{
private const string ImageFolderPath = @"C:\SomeImages";
public ObservableCollection<string> ImageFilePaths { get; } = new ObservableCollection<string>();
private void OnClick(object sender, RoutedEventArgs e)
{
this.ImageFilePaths.Clear();
var directoryInfo = new DirectoryInfo(ImageFolderPath);
var enumerationOptions = new EnumerationOptions();
foreach (string imageFilePath in directoryInfo.EnumerateFiles("*", enumerationOptions)
.Where(fileInfo => fileInfo.Extension is ".png" or ".jpg")
.Select(fileInfo => fileInfo.FullName))
{
this.ImageFilePaths.Add(imageFilePath);
}
}
}
主視窗.xaml
<Window>
<Button Content="Load Images"
Click="OnClick" />
<ListBox ItemsSource="{Binding RelativeSource={RelativeSource AncestorType=Window}, Path=ImageFilePaths}">
<ListBox.ItemTemplate>
<DataTemplate>
<Button>
<Image Height="96"
Width="96"
Source="{Binding}" />
</Button>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Window>
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/388596.html