【问题标题】:Trying to use custom DataTemplates inside a ViewRenderer in Xamarin for a UWP control尝试在 Xamarin 的 ViewRenderer 中使用自定义 DataTemplates 来实现 UWP 控件
【发布时间】:2016-09-12 15:11:25
【问题描述】:

我遇到了自定义渲染器的问题,我有点难过/卡住了。

我正在尝试在 Windows UWP 渲染器中使用以下代码行

ItemTemplate = (WDataTemplate)WApp.Current.Resources["ItemTemplate"]

我得到了一个资源注释发现异常,我只是不明白为什么

渲染器声明看起来像 公共类 Horizo​​ntalListViewRenderer : ViewRenderer

XAML 看起来像这样

<control:HorizontalListView ItemsSource="{Binding Items}">
    <control:HorizontalListView.ItemTemplate>
        <DataTemplate>
            <StackLayout Padding="15,0,15,0">
                 <Label Text="{Binding Title}" TextColor="#323232">
                      <Label.FontSize>
                          <OnPlatform x:TypeArguments="x:Double" Android="18" WinPhone="22" iOS="18" />
                      </Label.FontSize>
                 </Label>
            </StackLayout>
        </DataTemplate>
    </control:HorizontalListView.ItemTemplate>
</control:HorizontalListView >

我已经在 XF2.2 和 XF2.3 上尝试过 - 两者都有相同的问题

有人有什么想法或建议吗?

【问题讨论】:

    标签: xamarin xamarin.forms


    【解决方案1】:

    当你使用线路时

    ItemTemplate = (WDataTemplate)WApp.Current.Resources["ItemTemplate"]
    

    这是指 UWP 应用中的 Application.Resources。在您的 UWP 应用中转到您的 App.xaml,然后添加 ItemTemplate 定义,例如

        <Application.Resources>
            <DataTemplate x:Key="ItemTemplate">
                <forms:ItemControl HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch" />
            </DataTemplate>
        </Application.Resources>
    
    </Application>
    

    【讨论】:

    • 仅供参考,这是 CarouselView 所需的确切定义。
    • 亚当,谢谢你的建议。我同意这将作为一个可能的解决方案,不幸的是这不是我想要的。我正在寻找为什么要创建一个行为与开箱即用控件相同的自定义控件。如果没有注意到,标准控件都不需要使用应用程序级别的资源(仅供参考,这对性能不是很好)。开箱即用的控件都支持内联 ItemTemplate/DataTemplate 定义。
    • 您的建议的另一个缺点是它将控件限制为整个应用程序的 1 个模板,因为它有效地使用了一个硬编码名称,每个页面最多只能定义一次。那么,如果我在具有不同模板的单个页面上需要 4 或 5 个这样的控件,会发生什么?在您提供的示例中,这是不可能的,因为它们都将使用全局定义的模板。
    • Adam 如果您好奇的话,请看这里的第 63 行 github.com/xamarin/Xamarin.Forms/blob/master/…
    • 我不确定我是否理解正确。 DataTemplate 是特定于平台的,所有 UWP 标准控件都使用单个静态定义的模板。您在 XF 中定义不同的 DataTemplate,并将其插入到本地定义的数据模板中。WApp.Current.Resources["ItemTemplate"] 从本机应用程序而不是 XF 获取它。还有更多关于为什么它对性能不好的信息,我很想知道。
    猜你喜欢
    • 2019-10-08
    • 2018-04-15
    • 2018-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-16
    • 2020-05-31
    • 2021-04-05
    相关资源
    最近更新 更多