我正在尝试使用Reactangle
中的图片填充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));
}
}
但它引发了一个错误:The provided DependencyObject is not a context for this Freezable.
..对于为什么会发生这种情况有什么想法?
我已经阅读了this但是我可能无法应用解决方案,因为我没有从代码创建ImageBrush
背后...... ??
答案 0 :(得分:1)
为矩形指定名称
<Rectangle x:Name="rect" RadiusX="15" RadiusY="15"/>
然后创建一个新的ImageBrush并将其分配给Rectangle的Fill属性:
var fill = new ImageBrush(new BitmapImage(new Uri(ofpd.FileName)));
RenderOptions.SetBitmapScalingMode(fill, BitmapScalingMode.Fant);
rect.Fill = fill;