Home > Mobile >  In the following example from .Net Maui XAML 2009, why does the RelativeSource fail to get the Picke
In the following example from .Net Maui XAML 2009, why does the RelativeSource fail to get the Picke

Time:01-23

<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?

CodePudding user response:

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}}}" />

CodePudding user response:

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 />
  • Related