[英]In the following example from .Net Maui XAML 2009, why does the RelativeSource fail to get the Picker?
<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>
我的理解是,我可以通過在FindAncestor的AncestorType中指定“Picker”來獲取Picker控件,但似乎並非如此。 誰能解釋為什么?
如果我給 Picker 一個名字並將 RelativeSource 更改為 x:Reference 如下所示,我可以成功獲取它(“SampleBindable”屬性反映了 Picker 的 ItemsSource 的內容)。
<Picker x:Name="pick">
<local:SampleConverter SampleBindable="{Binding ItemsSource, Source={x:Reference pick}}" />
但是,每次只為這些綁定命名控件似乎有些多余……有誰知道避免命名 Picker 控件的方法嗎?
Source
通常用於靜態尋址位於其他地方的源。 如果你想爬樹尋找親戚父類,你可以使用RelativeSource
代替。 嘗試這個:
<local:SampleConverter SampleBindable="{Binding ItemsSource,
RelativeSource={RelativeSource AncestorType={x:Type Picker}}}" />
根據您的代碼,您沒有綁定到祖先。 官方文件說:
FindAncestor 和 FindAncestorBindingContext 相對綁定模式用於綁定到可視化樹中某種類型的父元素
選擇器不是父元素。 而且我好像只能在xaml里面找一個picker,好像是綁定到自己的。 所以你可以嘗試:
<local:SampleConverter SampleBindable="{Binding Source={RelativeSource Self}, Path=ItemsSource />
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.