How to use image files dynamically at runtime as button content in WPF?
Simply enumerate the folder and add the file paths of interest to a List
or ObservableCollection
and bind it to a ListBox
(or any ItemsControl
of choice). Define a DataTemplate
to render the image buttons. You can use the FileSystemWatcher
to observe directories for changes.
MainWindow.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);
}
}
}
MainWindow.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>
Loading image from the web at runtime in WPF
Funny indeed! Works alright at my other laptop now. Must be something with the firewall settings. And yeps, I've made things even simpler now. Binding the source of the image in XAML to just a string property I've set in a ViewModel class.
<Image x:Name="image1" Source ="{Binding MyPic}" Grid.Row="0"></Image>
class MyViewModel
{
public string MyPic {
get { return @"http://www.clipartkid.com/images/817/pic-of-german-flag-clipart-best-VkuN37-clipart.jpeg"; }
}
}
Thanks for the responses, and sorry for the confusion.
-Ron
Load Image at runtime from resource in WPF
It turns out that I should have used
Uri(@"pack://application:,,,/<MyProject>;component/images/tagimages/placeholder.png", UriKind.Absolute);
Dynamic loading of images in WPF
It is because the Creation was delayed.
If you want the picture to be loaded immediately, you can simply add this code into the init phase.
src.CacheOption = BitmapCacheOption.OnLoad;
like this:
src.BeginInit();
src.UriSource = new Uri("picture.jpg", UriKind.Relative);
src.CacheOption = BitmapCacheOption.OnLoad;
src.EndInit();
Image not displaying at runtime C# WPF
In your project:
- Create a folder say "img", right click on it and select add existing item add image to folder
- Go to properties of the added image, set
Build Action
asResource
andCopy To Output Directory
asCopy if newer
.
It worked for me.
In XAML
<Image HorizontalAlignment="Left" Name="MyImg" Height="80" Margin="273,147,0,0"
VerticalAlignment="Top" Width="100" Source="/img/Desert.jpg"/>
Bringing large image into view at runtime
The probably most simple way of asynchronously loading an image is via an asynchronous Binding. You would not have to deal with Threads or Tasks at all.
<Image Source="{Binding Image, IsAsync=True}"/>
A possible view model could look like shown below, where you must make sure that the Image
property getter can be called from a background thread.
public class ViewModel : ViewModelBase
{
private string imagePath;
private BitmapImage image;
public string ImagePath
{
get { return imagePath; }
set
{
imagePath = value;
image = null;
OnPropertyChanged(nameof(ImagePath));
OnPropertyChanged(nameof(Image));
}
}
public BitmapImage Image
{
get
{
lock (this)
{
if (image == null &&
!string.IsNullOrEmpty(imagePath) &&
File.Exists(imagePath))
{
using (var stream = File.OpenRead(imagePath))
{
image = new BitmapImage();
image.BeginInit();
image.CacheOption = BitmapCacheOption.OnLoad;
image.DecodePixelWidth = 200;
image.StreamSource = stream;
image.EndInit();
image.Freeze();
}
}
}
return image;
}
}
}
Related Topics
Difference Between Asynchronous Programming and Multithreading
Httpclient.Getasync(...) Never Returns When Using Await/Async
How to Remove All Namespaces from Xml With C#
When Should I Use Double Instead of Decimal
Still Confused About Covariance and Contravariance & In/Out
What Is App.Config in C#.Net - How to Use It
Why Do We Need Boxing and Unboxing in C#
If Async-Await Doesn't Create Any Additional Threads, Then How Does It Make Applications Responsive
Color Different Parts of a Richtextbox String
Remove Element of a Regular Array
How to Convert an Integer into Its Verbal Representation
C# Constructor Execution Order
How to Load a .Net Assembly At Runtime and Instantiate a Type Knowing Only the Name