How to bind image control to a file selected by user? - c#

I have an image file selected by user whose name is 'img'. How can I bind my Image control (given below) to this file?
<Image Source = "{Binding ImagePath}" />
I wrote:
ImagePath = new Uri(img.Path);
But it does not work. Can anyone help me?

After your image is loaded, create a BitmapImage.
var bi = new BitmapImage();
var fstream = await selectedFile.OpenAsync(FileAccessMode.Read);
bi.SetSource(fstream);
BImage = bi;
Then make sure your BImage property notifies the UI. I renamed ImagePath to BImage to clarify that it's not using the Path directly, but you can call it whatever you like.
private BitmapImage _bImage;
public BitmapImage BImage
{
get { return _bImage; }
set
{
_bImage= value;
NotifyPropertyChanged("BImage");
}
}
(Your XAML)
<Image Source = "{Binding BImage}" />

Related

Binding image StorageFile to XamlCropControl

I am working with XamlCropControl library here. I can't binding image from StorageFile to crop-control.
As for XamlCropControl, they do like that:
<xamlcrop:CropControl x:Name="Crop" ImageSource="ms-appx:///Assets/wrench.jpg" DesiredAspectRatio="1.0" />
But in my case, I need to bind an image that was picked from gallery then pass it to crop-control. I do like bellow, however it did not work at all.
public async void ImageReceiver(StorageFile image)
{
BitmapImage bitmapImage = new BitmapImage();
FileRandomAccessStream stream = (FileRandomAccessStream)await image.OpenAsync(FileAccessMode.Read);
bitmapImage.SetSource(stream);
ImgParam = bitmapImage;
}
private BitmapImage imgParam;
public WriteableBitmap ImgParam
{
get { return imgParam; }
set
{
imgParam = value;
RaisePropertyChanged("ImgParam");
}
}
And in xaml file:
<xamlcrop:CropControl x:Name="CropControl"
ImageSource="{Binding ImgParam, Mode=TwoWay}"
DesiredAspectRatio="1.0"
Background="Black"
Width="100"
Height="100"/>

How to add grid background Image in c#

I am trying to change images source or image background in c# when a button is click with xaml design UI.
<Grid x:Name="gridimage">
<Image x:Name="Image" stretch="Fill"/>
</Grid>
private void Button1_click(object sender, RoutedEventArgs e)
{
// NOT WORKING FOR ME
gridimage.Source = new BitmapImage (new Uri("location"));
gridimage.Background = ?
}
Assumed that there is an Assets folder in your Visual Studio project that contains an image file 2.png, and that the image file's Build Action is set to Resource, you would create a BitmapImage in code behind from a Pack URI like this:
var uri = new Uri("pack://application:,,,/Assets/2.png");
var bitmap = new BitmapImage(uri);
Then you would use the BitmapImage as Source of your Image control:
Image.Source = bitmap;
Or use it with an ImageBrush as Background of your Grid:
gridimage.Background = new ImageBrush(bitmap);

Bind Xaml bitmap image

I have bitmap image variable and i want to bind it to my xaml window.
System.Reflection.Assembly thisExe;
thisExe = System.Reflection.Assembly.GetExecutingAssembly();
string[] resources = thisExe.GetManifestResourceNames();
var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("SplashDemo.Resources.Untitled-100000.png");
Bitmap image = new Bitmap(stream);
And this is my xaml code
<Image Source="{Binding Source}" HorizontalAlignment="Left" Height="210" Margin="35,10,0,0" VerticalAlignment="Top" Width="335">
</Image>
can u assist me binding this bitmap variable to this xaml image by C# code?
If you really want to set it from C# code and not from inside XAML, you should use this easy solution described further on the MSDN reference:
string path = "Resources/Untitled-100000.png";
BitmapImage bitmap = new BitmapImage(new Uri(path, UriKind.Relative));
image.Source = bitmap;
But first, you need to give your Image a name so you can reference it from c#:
<Image x:Name="image" ... />
No need to reference Windows Forms classes.
If you insist on having the Image embedded into your Assembly, you need the following more lengthy code to load the image:
string path = "SplashDemo.Resources.Untitled-100000.png";
using (Stream fileStream = GetType().Assembly.GetManifestResourceStream(path))
{
PngBitmapDecoder bitmapDecoder = new PngBitmapDecoder(fileStream,
BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
ImageSource imageSource = bitmapDecoder.Frames[0];
image.Source = imageSource;
}
Here is some sample code:
// Winforms Image we want to get the WPF Image from...
System.Drawing.Image imgWinForms = System.Drawing.Image.FromFile("test.png");
// ImageSource ...
BitmapImage bi = new BitmapImage();
bi.BeginInit();
MemoryStream ms = new MemoryStream();
// Save to a memory stream...
imgWinForms.Save(ms, ImageFormat.Bmp);
// Rewind the stream...
ms.Seek(0, SeekOrigin.Begin);
// Tell the WPF image to use this stream...
bi.StreamSource = ms;
bi.EndInit();
Click here to view reference
If you are using WPF, right click your image in your project and set the Build Action to Resource. Assuming your image is called MyImage.jpg and is in a Resources folder in your project, you should be able to reference it directly in your xaml without using any C# code. Like this:
<Image Source="/Resources/MyImage.jpg"
HorizontalAlignment="Left"
Height="210"
Margin="35,10,0,0"
VerticalAlignment="Top"
Width="335">
</Image>

Bind image to datagrid using resources

I am trying to retrieve the image from resource file and tryin to bind it to the datagrid of my WPF application.
The datagrid is somewhat like this:
<DataGridTemplateColumn Header="Image" Width="45">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Image Source="{Binding Path=Icon}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
And Image is a property of type image of my MVVm class like this:
public Image Icon
{
get { return _licenseImage; }
set { _licenseImage = value;
PropertChanged("Icon");}
}
And in the code behind Im tryin to do something like this to get image from resource file and tryin to bind it to datagrid column.
ResourceManager resourceManager =
new ResourceManager("Resources.Images", Assembly.GetExecutingAssembly());
BitMap bitmap = resourceManager.GetObject("okimage") as BitMap;
Image image = bitmap;
return image;
I can see that image is populated but it is not displaying in the grid.
You should bind to an ImageSource instead of Image.
we use this helper class:
public static class ImageSourceHelper
{
public static ImageSource GetResourceImage(string resourcePath)
{
return GetResourceImage(Assembly.GetCallingAssembly(), resourcePath);
}
public static ImageSource GetResourceImage(Assembly resourceAssembly, string resourcePath)
{
if (string.IsNullOrEmpty(resourcePath)) return null;
var assembly = resourceAssembly.GetName().Name;
const string uriFormat = "pack://application:,,,/{0};component/{1}";
if (!UriParser.IsKnownScheme("pack")) new System.Windows.Application();
var uri = new Uri(string.Format(uriFormat, assembly, resourcePath), UriKind.RelativeOrAbsolute);
return BitmapFrame.Create(uri);
}
public static ImageSource ConvertFromGdiBitmap(Bitmap bitmap)
{
return Common.SystemAbstraction.Media.ImageConverter.ConvertToBitmapSource(bitmap);
}
public static Bitmap ConvertToGdiBitmap(ImageSource imageSource)
{
return Common.SystemAbstraction.Media.ImageConverter.ConvertToBitmap(imageSource as BitmapSource);
}
}
It creates an ImageSource from Bitmap or resource images.
Usage is
img.Source = ImageSourceHelper("Path/To/Your/Image.png");
or
var resourceAssembly = // get resource assembly...
img.Source = ImageSourceHelper(resourceAssembly, "Path/To/Your/Image.png");
if the image is contained in an other assembly than the currently calling assembly.
The path of your image is the path starting at the project file root of your assembly.
Say you have an folder images your path will be "images/somepicture.png".
I think the problem is that you are binding to the wrong property. Try this:
<Image Source="{Binding Path=Icon}" />

Why doesn't the SourceUpdated event trigger for my Image Control in WPF?

I have an image control on a Window in my WPF project
XAML:
<Image
Source="{Binding NotifyOnSourceUpdated=True, NotifyOnTargetUpdated=True}"
Binding.SourceUpdated="bgMovie_SourceUpdated"
Binding.TargetUpdated="bgMovie_TargetUpdated" />
In code I am changing the source of the image
C#:
myImage = new BitmapImage();
myImage.BeginInit();
myImage.UriSource = new Uri(path);
myImage.EndInit();
this.bgMovie.Source = myImage;
But the bgMovie_SourceUpdated event is never triggered.
Can anyone shed some light on what I'm doing wrong?
By assiging a value directly to the Source property, you're "unbinding" it... Your Image control is not databound anymore, it just has a local value.
In 4.0 you could use the SetCurrentValue method:
this.bgMovie.SetCurrentValue(Image.SourceProperty, myImage);
Unfortunately this method isn't available in 3.5, and there is no easy alternative...
Anyway, what are you trying to do exactly ? What is the point of binding the Source property if you're setting it manually anyway ? If you want to detect when the Source property changes, you can use the DependencyPropertyDescriptor.AddValueChanged method:
var prop = DependencyPropertyDescriptor.FromProperty(Image.SourceProperty, typeof(Image));
prop.AddValueChanged(this.bgMovie, SourceChangedHandler);
...
void SourceChangedHandler(object sender, EventArgs e)
{
}
By hard-coding the Source in the code, you are breaking the Binding in your XAML.
Instead of doing that, bind to a property that you set using (most of) the same code above. Here's one way to do that.
XAML:
<Image Name="bgMovie"
Source="{Binding MovieImageSource,
NotifyOnSourceUpdated=True,
NotifyOnTargetUpdated=True}"
Binding.SourceUpdated="bgMovie_SourceUpdated"
Binding.TargetUpdated="bgMovie_TargetUpdated" />
C#:
public ImageSource MovieImageSource
{
get { return mMovieImageSource; }
// Set property sets the property and implements INotifyPropertyChanged
set { SetProperty("MovieImageSource", ref mMovieImageSource, value); }
}
void SetMovieSource(string path)
{
myImage = new BitmapImage();
myImage.BeginInit();
myImage.UriSource = new Uri(path);
myImage.EndInit();
this.MovieImageSource = myImage;
}

Categories

Resources