wpf icon indicating copy to clipboard operation
wpf copied to clipboard

[API Proposal]: Fallback when binding target type does not match

Open Laniusexcubitor opened this issue 9 months ago • 4 comments

Background and motivation

Currently when we use a binding with an interface we get a binding error or warning when the source type does not implement the interface: TargetException:'System.Reflection.TargetException: Object does not match target type.
Sometimes this is completely ok, but we get a nasty binding warning in XAML Binding failures when a FallBack value has been set otherwise a binding error is generated. I propose a new property on a binding like FallbackOnUnmatchedTargetType that will suppress the resulting binding warning.

API Proposal

public class Binding : BindingBase
{
    // ...
    [DefaultValue(false)]
    public bool FallbackOnUnmatchedTargetType { get; set }
}

API Usage

<TextBox Text="{Binding Path=(namespace:IInterface.SomeProperty), FallbackOnUnmatchedTargetType=True, FallBackValue={x:Null}}" />

Alternative Designs

No response

Risks

This would not change the current behavior except of suppressing the current warning/error. Using the property developers are saying that they know that there will be unmatched objects, and they don't need a warning about it.

Laniusexcubitor avatar Apr 09 '25 12:04 Laniusexcubitor

API is not a requirement for suppressing this behavior, right? One another way could be addition of an app context switch which can suppress the behavior.

dipeshmsft avatar Apr 11 '25 04:04 dipeshmsft

That would suppress the binding errors globally. The proposed API would allow to suppress this on a per binding scope. It's like suppressing an analyzer locally because the code was reviewed vs just suppressing all. I want to be warned about binding errors. But I'd like to have the option to flag single bindings as being tolerant against datacontexts not implementing the interface the binding path expects. Currently I often use an IValueConverter that allows to check for a type and set bindings via a trigger on that. But that tactic does not work for all circumstances.

Laniusexcubitor avatar Apr 11 '25 05:04 Laniusexcubitor

I agree that API changes shouldn't be used to get rid of warnings. It also seems to be useful to have a warning saying the fallback value is being used. What is the issue with getting a warning?

miloush avatar Apr 11 '25 11:04 miloush

The issue with getting a warning is that we have warnings that must be ignored. But this tends to lead to ignoring of all additional warnings and then you can just turn of the warnings completely. If if some developers do care about new warnings, they always have to go through the ignorable warning clutter which is time consuming and frustrating.

Laniusexcubitor avatar Apr 11 '25 14:04 Laniusexcubitor