1

I am trying to fill a Reactanglewith an image from OpenFileDialog.

XAML

<Rectangle RadiusX="15" RadiusY="15">
<Rectangle.Fill>
      <ImageBrush x:Name="userpic" RenderOptions.BitmapScalingMode="Fant" ImageSource="/icons/usericon.png"/>
</Rectangle.Fill>
</Rectangle>

C#

private void LoadImg() {
    System.Windows.Forms.OpenFileDialog ofpd = new System.Windows.Forms.OpenFileDialog();
    ofpd.Filter = "Image Files(*.BMP;*.JPG;*.PNG;*.JPEG)|*.BMP;*.JPG;*.PNG;*.JPEG";
    ofpd.Title = "Add a photo";
    if ((ofpd.ShowDialog == System.Windows.Forms.DialogResult.OK)) {
        userpic.ImageSource = new BitmapImage(new Uri(ofpd.FileName));
    }

}

But it's throwing an error : The provided DependencyObject is not a context for this Freezable...Any idea on why this is happening ?

I already read this but maybe i cant apply the solution as i am not creating the ImageBrush from code-Behind...??

1 Answers1

1

Assign a Name to the Rectangle

<Rectangle x:Name="rect" RadiusX="15" RadiusY="15"/>

Then create a new ImageBrush and assign it to the Rectangle's Fill property:

var fill = new ImageBrush(new BitmapImage(new Uri(ofpd.FileName)));
RenderOptions.SetBitmapScalingMode(fill, BitmapScalingMode.Fant);
rect.Fill = fill;
Clemens
  • 123,504
  • 12
  • 155
  • 268
  • Yes,it works...Can u tell me what was the problem ? What was causing this ? –  Mar 09 '18 at 19:49
  • 2
    Not sure, but the ImageBrush declared in XAML may be frozen after creation, so that you could not assign a new value to its ImageSource property. You could inspect the exception's call stack. – Clemens Mar 09 '18 at 19:54