Reputation: 22006
I have a folder inside my project which includes some images, for example: "Cards/1-1.png".
I have an Image element linked with XAML, and I'm trying to set it's Source
property programmatically:
BitmapImage bitmap = new BitmapImage();
string filename= "Cards/1-1.png";
bitmap.UriSource = new Uri("/Poker;component/" + filename, UriKind.Relative);
cardImage1.Source= bitmap; // myImage linked with XAML
I try to fill 5 images, and I checked the filenames, they're correct. But the images are still empty (they're inside the StackPanel on the right):
<StackPanel Orientation="Horizontal" DockPanel.Dock="Right"
Background="Green">
<Image Width="80" Height="100" Margin="10" x:Name="cardImage1"/>
<Image Width="80" Height="100" Margin="10" x:Name="cardImage2"/>
<Image Width="80" Height="100" Margin="10" x:Name="cardImage3"/>
<Image Width="80" Height="100" Margin="10" x:Name="cardImage4"/>
<Image Width="80" Height="100" Margin="10" x:Name="cardImage5"/>
</StackPanel>
Upvotes: 0
Views: 1790
Reputation: 81313
BitmapImage implements ISupportInitialize interface which means any property change after initialization of object will be ignored unless wrap in BeginInit()
and EndInit()
.
Quote from MSDN:
BitmapImage implements the ISupportInitialize interface to optimize initialization on multiple properties. Property changes can only occur during object initialization. Call BeginInit to signal that initialization has begun and EndInit to signal that initialization has completed. After initialization, property changes are ignored.
BitmapImage objects created using the BitmapImage constructor are automatically initialized and property changes are ignored.
So, change your code to wrap property initialization like this:
BitmapImage bitmap = new BitmapImage();
string filename= "Cards/1-1.png";
bitmap.BeginInit();
bitmap.UriSource = new Uri("/Poker;component/" + filename, UriKind.Relative);
bitmap.EndInit();
cardImage1.Source= bitmap; // myImage linked with XAML
OR
Initialize all relevant properties at time of initialization by passing Uri in constructor like this:
string filename= "Cards/1-1.png";
BitmapImage bitmap = new BitmapImage(new Uri("/Poker;component/" + filename,
UriKind.Relative));
Upvotes: 1
Reputation: 1590
I tried this code but it isn't working, i found a way to do what you exactly need:
cardImage1.Source = new BitmapImage(new Uri("/Poker;component/" + filename, UriKind.Relative));
you assigned BitmapImage.Source to Image.Source, i think that's why it isn't working.
Hope it helps.
Upvotes: 1