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

cjk
  • 1
  • 1

2 Answers2

0

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}}}" />
AceGambit
  • 423
  • 3
  • 11
  • Sorry for the lack of information. This problem occurs in MAUI, not WPF, and in MAUI, relative binding is set for the ```Source``` property. [Reference](https://learn.microsoft.com/en-us/dotnet/maui/fundamentals/data-binding/relative-bindings?view=net-maui-7.0#bind-to-an-ancestor) Please try again with the MAUI project. – cjk Jan 20 '23 at 14:57
  • I tried the code presented in WPF as well, but it still did not work as expected. – cjk Jan 23 '23 at 18:28
0

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 />
Liyun Zhang - MSFT
  • 8,271
  • 1
  • 2
  • 14
  • The code you presented tries to bind ```SampleConverter.ItemsSource```, not ```Picker.ItemsSource```. Have you actually checked the behavior of that code? It did not work as intended, at least in my environment. – cjk Jan 23 '23 at 18:21
  • So binding to an ancestor and binding to setl both work in this contidtion. Because there is no parent element. – Liyun Zhang - MSFT Jan 24 '23 at 10:46