In the following example from .Net Maui XAML 2009, why does the RelativeSource fail to get the Picker?

359 views Asked by At
<Picker>
    <Picker.ItemsSource>
        <c:List x:TypeArguments="x:String">
            <x:String>apple</x:String>
            <x:String>orange</x:String>
        </c:List>
    </Picker.ItemsSource>
    <Picker.SelectedItem>
        <Binding>
            <Binding.Converter>
                <local:SampleConverter SampleBindable="{Binding ItemsSource, Source={RelativeSource FindAncestor, AncestorType={x:Type Picker}}}" />
            </Binding.Converter>
        </Binding>
    </Picker.SelectedItem>
</Picker>

My understanding was that I could get the Picker control by specifying "Picker" in the AncestorType of FindAncestor, but this does not seem to be the case. Can anyone explain why?

If I give the Picker a name and change the RelativeSource to x:Reference as shown below, I can get it successfully (the "SampleBindable" property reflects the contents of the ItemsSource of the Picker).

<Picker x:Name="pick">
<local:SampleConverter SampleBindable="{Binding ItemsSource, Source={x:Reference pick}}" />

but, It seems somewhat redundant to name the control every time just for these bindings... does anyone know of a way to avoid having to name the Picker control?

2

There are 2 answers

2
AceGambit On

Source is typically used for statically addressing a source located elsewhere. If you want to climb the tree to find a relative parent, you can use RelativeSource instead. Try this:

<local:SampleConverter SampleBindable="{Binding ItemsSource, 
    RelativeSource={RelativeSource AncestorType={x:Type Picker}}}" />
2
Liyun Zhang - MSFT On

According to your code, you were not binding to an ancestor. The official document said:

The FindAncestor and FindAncestorBindingContext relative binding modes are used to bind to parent elements, of a certain type, in the visual tree

The picker is not a parent element. And I can seem only one picker in the xaml. It seems be binding to self. So you can try:

<local:SampleConverter SampleBindable="{Binding Source={RelativeSource Self}, Path=ItemsSource />