Reputation:
I am trying to fill a Reactangle
with 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...??
Upvotes: 1
Views: 1361
Reputation: 128084
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;
Upvotes: 1