The provided DependencyObject is not a context for this Freezable WPF c#

▼魔方 西西 提交于 2021-01-28 08:19:07

问题


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:


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;


来源:https://stackoverflow.com/questions/49200779/the-provided-dependencyobject-is-not-a-context-for-this-freezable-wpf-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!