In XAML:
<Rectangle Stroke="Aqua" Opacity="0.7" StrokeThickness="10" Canvas.Left="24" Canvas.Top="22" Height="86" Width="102">
<Rectangle.Fill>
<ImageBrush ImageSource="C:\Users\xiaorui.dong\Pictures\profile.jpeg"></ImageBrush>
</Rectangle.Fill>
</Rectangle>
XAML works fine, but how to create the above ImageBrush in C# code:
C# should be like this:
Rectangle rectangle = new Rectangle();
rectangle.StrokeThickness = 10;
rectangle.Height = 200;
rectangle.Width = 100;
rectangle.SetValue(Canvas.LeftProperty, 100d);
rectangle.SetValue(Canvas.TopProperty, 100d);
rectangle.Fill = new ImageBrush(new BitmapImage(new Uri(@"C:\Users\xiaorui.dong\Pictures\profile.jpeg")));
I'm guessing the problem is with locating the image and that the exception you're getting is because you don't provide the UriKind
parameter. Try giving UriKind.Relative
as a parameter to the Uri
:
rectangle.Fill = new ImageBrush(new BitmapImage(
new Uri(@"C:\Users\xiaorui.dong\Pictures\profile.jpeg", UriKind.Relative)));
In c# you can use it like , first thing is remove the fill from XAML then use the same code in c# as you have used it . It must work.
ImageBrush ib = new ImageBrush();
ib.ImageSource = new BitmapImage(new Uri("your path",UriKind.Relative));
rectangle.Fill = ib;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With