Search code examples
c#maui

We can't we simplify BindingContext="{Binding Source={RelativeSource Self}}" to BindingContext="{RelativeSource Self}"?


It is a trivial example to illustrate the problem. I want to make the background color depend on the input.

<Entry
    BackgroundColor="{Binding Source={RelativeSource Self}, Path=Text}" />
// or
<Entry
    BindingContext="{Binding Source={RelativeSource Self}}"
    BackgroundColor="{Binding Text}" />

Both work with the following output.

enter image description here

However if I simplify it as follows, it no longer works.

<Entry
    BindingContext="{RelativeSource Self}"
    BackgroundColor="{Binding Text}" />

As a comparison we can simplify

ItemsSource="{Binding Source={StaticResource people}}"

to

ItemsSource="{StaticResource people}"

Question

What is the culprit?


Solution

  • The RelativeSource markup extension provides a RelativeBindingSource instance, which is not the actual object that you can fetch info from (however, it can be used as a source for the Binding extension).

    In your first two examples the binding context for Entry is bound to actual object returned by {Binding}.

    Compare that to ItemsSource, which needs a source and not actual object.