xamarin.forms - 在 Xamarin.Forms 中运行时访问 DataTemplate 内的 View

标签 xamarin.forms datatemplate

我想知道是否有办法在 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/

相关文章:

c# - 如何为 WPF TreeView 设置 DataTemplate 以显示列表的所有元素?

c# - 使用 View 或存储过程在 Azure 移动应用程序中进行离线数据同步

c# - XAML - IValueConverter 和Behavior 相互冲突,导致发生无限循环

c# - 如何以编程方式访问 DataTemplate 的关联数据类型?

c# - 如何向 ItemsControl 中的 WPF 按钮添加相同的命令

wpf - 当 ContentControl 的内容为 null 或为空时,显示默认的 DataTemplate?

wpf - 尽管样式,ComboBoxItem 继续抛出绑定(bind)错误

c# - Xamarin 表单绑定(bind)。如何根据某些条件显示 3 个不同字符串中的 1 个

xamarin - 错误 : Error initializing task XamlG: Not registered task XamlG

c# - Xamarin Forms 管理闹钟