I have this ResourceDictionary in Main.xaml:
<Window.Resources>
<ResourceDictionary>
<BitmapImage x:Key="Customer" UriSource="Icons/customer.png"/>
<BitmapImage x:Key="Project" UriSource="Icons/project.png"/>
<BitmapImage x:Key="Task" UriSource="Icons/task.png"/>
</ResourceDictionary>
</Window.Resources>
I initially set the image using:
<Image Name="TypeIcon" HorizontalAlignment="Left" VerticalAlignment="Center"
Source="{StaticResource Customer}" Height="16" Width="16"/>
I'm trying to change TypeIcon's Source from Customer to Project in a C# method.
I've tried using:
TypeIcon.Source = "{StaticResource Project}";
But I get this error:
Cannot implicitly convert type string to System.Windows.Media.ImageSource
I've tried defining the image using new ImageSource(), but this doesn't work either.
How can I change the image's Source programmatically in C#?
After much Googling, whilst writing this question, I figured out how to do it:
TypeIcon.Source = (ImageSource) Resources["Project"];
It is not for static resources but perhaps will be useful anyway... :)
i.e. how to set background for Grid dynamically
var myBrush = new ImageBrush();
var image = new Image
{
Source = new BitmapImage(
new Uri(
"pack://application:,,,/YourAppName;component/Images/Boo.png"))
};
myBrush.ImageSource = image.Source;
MainGrid.Background = myBrush;
i.e. how to set icon of the app dynamically
var idleIco = new Image
{
Source = new BitmapImage(
new Uri(
"pack://application:,,,/YourAppName;component/Images/idle.ico"))
};
SomeObjectYouAreUsingToSet.IconSource =idleIco.Source;
You can use the ImageSourceConverter class to get what you want, for example:
img1.Source = (ImageSource)new ImageSourceConverter().ConvertFromString("/Assets/check.png");
Related
I want to add a Background colour and 9 Foreground Image to 9 buttons from code.
I wish to change the images from C# not in WPF / xaml.
The Background colour works OK using:
button1.Background.SetValue(SolidColorBrush.ColorProperty, Windows.UI.Colors.Red);
Windows forms has an easy solution using:
pictureBox1.Image = Properties.Resources.P1; // this does not work for UWP
What I have tried so far ends up in error messages:
I have changed the Build Action property of P1.png from Content to PRIResource with no success.
string url = "../../Images/P1.png";
//string url = "PW.png";
image1.Source = new BitmapImage(new Uri(url, UriKind.Relative)); //.Uri cannot be converted into a Windows.Foundation.Uri.
//image1.Source = new BitmapImage(new Uri(url, UriKind.Absolute)); //format of url could not be determined
<Button x:Name="button1" Content="Button" Grid.Column="0" Grid.Row="0"
Tag="1" Background="Gray" Padding="0" UseLayoutRounding="False"
HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Click="button1_Click">
<Button.Foreground>
<ImageBrush Stretch="Fill" ImageSource="P1.PNG"/>
</Button.Foreground>
</Button>
Solution:
To insert image to Button in C# using VS2015, UWP and Windows 8.1:
Add an Image to the front of your Button. eg Name = button1 and imageX.
Ensure that you set “Build Action” Properties of *.png to Content.
enter code hereImageBrush imageBrush = new ImageBrush();
imageBrush.ImageSource = new BitmapImage(new Uri("ms-appx:///Images/PW.PNG"));
button1.Background = imageBrush;
BitmapImage bitImage = new BitmapImage();
bitImage.UriSource = new Uri("ms-appx:///Images/PW.PNG");
imageX.Source = bitImage;
Thanks Romasz for your assistance.
I have a BitmapImage, and want to set it as Background of Grid. I have tried this
xaml:
<Grid x:Name="ContentPanel">
<Grid.Background>
<ImageBrush x:Name="imgBg" />
</Grid.Background>
</Grid>
c#:
BitmapImage bmp = new BitmapImage();
bmp.DecodePixelWidth =(int) scrnWidth;
bmp.DecodePixelHeight = (int)scrnHeight;
bmp.SetSource(e.ChosenPhoto);
ImageBrush ib = new ImageBrush() { ImageSource = bmp };
imgBg.ImageSource = ib.ImageSource;
Output: Output is just black.
Question: using above code I am unable to set bitmapimage as background of Grid element, Am I missing something ?
Update I knew, it works fine when we set image as background to grid like:
ImageBrush ib = new ImageBrush() { ImageSource = bmp };
ContentPanel.Background = ib;
But I need to use xaml way, Question is same.
<Grid x:Name="ContentPanel">
<Grid.Background>
<ImageBrush Stretch="None"
ImageSource="Your Path/source"
AlignmentY="Center"
AlignmentX="Center" />
</Grid.Background>
</Grid>
This might help you, cant promise you it will but try it. was found on this post.
Here
Having the next XAML code
<Window.Resources >
<ImageBrush x:Key="tile" ImageSource="afraid.png"
Opacity=" 20" TileMode="Tile"
ViewportUnits="Absolute"
Viewport=" 0,0,32,32"
></ImageBrush>
</Window.Resources>
I want to change the image by c# code, during the run-time
I have the next code to do this, but the code does not work & I don`t know the reason:
ImageBrush img = ( ImageBrush )this.FindResource( "tile" );
ImageSourceConverter conv = new ImageSourceConverter();
ImageSource src = ( ImageSource )conv.ConvertFromString( "mad.png" );
img.ImageSource = src;
Please refer to this answer.
Try this, create a BitmapImage from a file and set it as the ImageSource of the ImageBrush.
ImageBrush img = (ImageBrush)this.FindResource("tile");
//change the imagesource in runtime,
img.ImageSource = new BitmapImage(new Uri("mad.png", UriKind.Relative));
In c# I am making an application using the xaml designer.
PROBLEM: IF I CHANGE THE IMAGE SOURCE INTO ANOTHER IMAGE SOURCE, NOTHING APPEARS: THOUGH, IF THE IMAGE WAS ALREADY DEFINED, IT CHANGED INTO "NULL" (NO IMAGE)
I have used a method (which I found on the web) to change an imagesource (string) into an image(object).
I've tried multiple times to change the image source of some xaml pictures by just changes the imagesource in xaml into another image (that I put in the project) but unfortunately the image is not visible when I do it this way.
The image and method I used are the following ones:
ms-appx:///Assets/bank_employee.jpg"
imageFromXaml.Source = imgCreatedFromMethod.Source;
private static Image srcToImage(string source)
{
Uri imageUri = new Uri(source);
BitmapImage imageBitmap = new BitmapImage(imageUri);
Image img = new Image();
img.Source = imageBitmap;
return img;
}
Does anyone of you know what the problem could be?
I had a similar problem, and this worked for me:
var imageSource = new BitmapImage();
imageSource.BeginInit();
imageSource.StreamSource = memoryStream;
imageSource.CacheOption = BitmapCacheOption.OnLoad;
imageSource.EndInit();
Have you tried binding the source in XAML to a URI and then updating that?
Like this:
<Image Source="{Binding ImageUri}" />
Then having a property somewhere in your datacontext which would be like:
public class myClass: INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private Uri imageUri;
public Uri ImageUri
{
get
{
return imageUri;
}
set
{
imageUri = value;
if(PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("ImageUri"));
}
}
}
}
Have you verified that your method actually succeeds and returns the correct image source? If it does there should be no problem reassigning Source. If you load the newly created image itself into the UI, does it retain its source?
this.Content = imgCreatedFromMethod; // where "this" is the window
By the way, it would not be necessary to implement your own conversion function. If you have a string that would be valid as XAML, you can directly call the converter that the XAML parser uses to build an image source:
using System.Globalization;
using System.Windows.Media;
string stringValue = ...
ImageSourceConverter converter = new ImageSourceConverter();
ImageSource imageSource = converter.ConvertFrom(
null, CultureInfo.CurrentUICulture, stringValue);
The converter instance (an ImageSourceConverter in this case) can also be retrieved dynamically by System.ComponentModel.TypeDescriptor.GetConverter(typeof(TypeToConvertTo)).
This conversion will also be done automatically if you use data-binding as in TylerD87's answer. You can also look into triggers and define both images in the style like this:
<Image>
<Image.Style>
<Style TargetType="Image">
<Setter Property="Source" Value="original path" />
<Style.Triggers>
<Trigger ...>
<Setter Property="Source" Value="new path" />
</Trigger>
</Style.Triggers>
</Style>
</Image.Style>
</Image>
I'm trying to change the background image set by xaml this way:
<s:SurfaceWindow.Resources>
<ImageBrush x:Key="WindowBackground"
Stretch="None" Opacity="0.6" ImageSource="pack://application:,,,/Resources/img/bg/Default.jpg"/>
</s:SurfaceWindow.Resources>
by using the following code in a method:
sessionWindow.SetValue(ImageBrush.ImageSourceProperty, "..//..//Resources//img//bg//Aqua.jpg");
where sessionWindow is the the actual window.
It throws the exception in the title
The ImageBrush.ImageSource property is of type ImageSource.
Therefore, you need to set it to an ImageSource instance.
Also, your path is wrong.
For example:
sessionWindow.SetValue(ImageBrush.ImageSourceProperty,
new BitmapImage(
new Uri(#"..\..\Resources\img\bg\Aqua.jpg", UriKind.Relative)
)
);
However, this won't actually change the background - Window doesn't have an ImageSource property.
Instead, you should set the Window's Background property, like this:
sessionWindow.Background = new ImageBrush {
ImageSource = new BitmapImage(
new Uri(#"..\..\Resources\img\bg\Aqua.jpg", UriKind.Relative)
)
};