我想知道是否有办法在 Xamarin.Forms 的 ListView 中获取对 DataTemplate 内 View 的引用。
假设我有这个 xaml:
<ListView x:Name="ProductList" ItemsSource="{Binding Products}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout BackgroundColor="#eee" x:Name="ProductStackLayout"
Orientation="Vertical" Padding="5" Tapped="ListItemTapped">
<Label Text="{Binding Name}"
Style="{DynamicResource ProductPropertiesStyle}"/>
<Label Text="{Binding Notes}" IsVisible="{Binding HasNotes}"
Style="{DynamicResource NotesStyle}"
/>
<Label Text="{Binding Date}"
Style="{DynamicResource DateStyle}"
/>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
我希望能够在 ListView 的每一行中获取对名为“ProductStackLayout”的 StackLayout 的引用。我需要在页面出现时执行此操作,以动态操作其内容(对于某些无法通过数据绑定(bind)实现的操作),因此我无法利用源自 DataTemplate 中的元素的事件处理程序中传递的 View 引用本身就像 ItemTapped 或类似的。
据我所知,在 WPF 或 UWP 中,可以借助 VisualTreeHelper 类来实现类似的功能,但我认为 Xamarin.Forms 中没有此类的等价物。
最佳答案
是的,可以访问使用 DataTemplate
创建的 View 在运行时。 Hook BindingContextChanged
DataTemplate
内 View 的事件来自 XAML。在事件回调中,从 DataTemplate
创建的 View 可以使用 sender 参数访问。您需要对发送者进行类型转换才能访问 View ,因为发送者被装箱为对象类型。
或者,您可以使用 DataTemplate 选择器根据您的对象创建 View 。
关于xamarin.forms - 在 Xamarin.Forms 中运行时访问 DataTemplate 内的 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49373982/