简体   繁体   中英

Error Binding ImageSource to ImageBrush

I have a class called MyUser. It contains a public property "Image" as follows

private ImageSource _Image;

public ImageSource Image
{
    get { return _Image; }
    set
    {
        if (value != _Image)
        {
            _Image = value;
            OnPropertyChanged("Image");
        }
    }
}

I have a WPF UserControl that contains a setter to fill a path with that user's image. (User is a MyUser object from the ViewModel)

<Setter Property="Fill">
    <Setter.Value>
        <ImageBrush ImageSource="{Binding Path=User.Image}"
                    Stretch="UniformToFill" />
    </Setter.Value>
</Setter>

I am getting an error during runtime (not an exception)

System.Windows.Data Error: 2 : Cannot find governing FrameworkElement or FrameworkContentElement for target element. BindingExpression:Path=User.Image; DataItem=null; target element is 'ImageBrush' (HashCode=21084988); target property is 'ImageSource' (type 'ImageSource')

The image is showing up perfectly fine. Why am I getting this error? Is this something I should be concerned about?

Thanks for all your help! Mo

Please read the answer of the similar error message . Microsoft says it's a minor bug in WPF but not worthy to be looked at beacuse it does not effect the runtime behavior.

Once I had a similar message. My problem was, that WPF could not determine one FrameworkElement to inherit the DataContext from, which belongs either to the Visual or to the Logical Tree. I interpreted it as if it assumed the first FrameworkElement in the VisualTree . So I think this message should be a hint for this behavior.

In these terms you should check whether your container or usercontrol or what ever you are using, belongs to the visual/logical tree.

Otherwise you could try to determine the DataContext explicitly by specifying it via ElementName=... or RelativeSource={RelativeSource FindAncestor, AncestorType=...} .

But have you tried to diagnose this binding? Using the namespace xmlns:diag="clr-namespace:System.Diagnostics;assembly=WindowsBase" and adding , diag:PresentationTraceSources.TraceLevel=High to your binding, you should be able to determine what is going on there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM