Search code examples
c#wpfbindingruntime-errorshader

Getting a runtime error for a binding that actually works


In a .NET 7.0 WPF desktop application, I have this style that applies a custom grayscale pixel shader to an image when the image is disabled. The style is defined in my App.xaml file :

<Style TargetType="Image" x:Key="GrayscaleImageStyle">
  <Style.Triggers>
    <Trigger Property="IsEnabled" Value="False">
      <Setter Property="Effect">
        <Setter.Value>
          <shaders:GrayscaleEffect Input="{Binding RelativeSource={RelativeSource Self}, Path=Source}"/>
        </Setter.Value>
      </Setter>
      <Setter Property="Opacity" Value="0.5"/>
    </Trigger>
  </Style.Triggers>
</Style>

Now the style is working perfectly fine and the pixel shader is correctly applied to an image that have IsEnabled set to false.

Yet I noticed that at runtime, I get a bunch of error messages in the output debug window like this one:

System.Windows.Data Error: 40 : BindingExpression path error: 'Source' property not found on 'object' ''GrayscaleEffect' (HashCode=1132111)'. BindingExpression:Path=Source; DataItem='GrayscaleEffect' (HashCode=1132111); target element is 'GrayscaleEffect' (HashCode=1132111); target property is 'Input' (type 'Brush')

I have tried some things (such as using an ImageSource to Brush converter (which was never called) or using a binding object) to no avail. The messages are still plenty and as I mentionned, this even if the effect works perfectly implying that the binding is ineeded working.

Any idea of what is going on and how I can get rid of these seamingly useless messages ?


Solution

  • I was so puzzled that the effect was working despite the binding showing me an error that I realized that the input of the effect must be set internally automatically so I removed the binding altogether. Voilà ! Effect still working; errors gone !

    <Style TargetType="Image" x:Key="GrayscaleImageStyle">
      <Style.Triggers>
        <Trigger Property="IsEnabled" Value="False">
          <Setter Property="Effect">
            <Setter.Value>
              <shaders:GrayscaleEffect/>
            </Setter.Value>
          </Setter>
          <Setter Property="Opacity" Value="0.5"/>
        </Trigger>
      </Style.Triggers>
    </Style>
    

    Hope this helps somebody else.