【问题标题】:XAML : Set Label Margin inside a DataTemplateXAML:在 DataTemplate 中设置标签边距
【发布时间】:2018-07-31 05:07:54
【问题描述】:

我在资源字典中直接有一个 DataTemplate。模板内部是一个标签。边距属性没有按照我的预期应用(没有效果)

<DataTemplate x:Key="HeaderContainerStyle">
    <Label Margin="10" Text="{Binding}"/>
</DataTemplate>

我无法解决边界问题,因为它看起来是非法的 (?)

<DataTemplate x:Key="HeaderContainerStyle">
    <Border Padding="10">
        <Label Text="{Binding}"/>
    </Border>
</DataTemplate>

我收到一条错误消息,提示无法解析符号边框。

当我尝试在 ViewCell 中添加它时,应用程序会抛出异常:

System.ArgumentException:值是 HeaderTemplate 的无效值 参数名称:值

【问题讨论】:

  • 你已经用 [wpf] 和 [xamarin] 标记了它,但显然不能同时使用。它是哪一个?我猜是 Xamarin Forms,因为 Border 显然是 WPF 中的有效类型。

标签: wpf xaml xamarin margin padding


【解决方案1】:

在 Xamarin.Forms 中没有 Border 类。相反,您应该使用我认为与 WPF 中的 Border 等效的 Frame 类。

就像@Nick 所说,如果您想在 Xamarin.Forms 中使用 DataTemplates,您需要在 DataTemplate 中添加 ViewCell,然后在其中添加下一个元素(例如 Grid、StackLayout 或 Label)。

如果涉及到 Padding,在 Xamarin.Forms 中它仅适用于布局(例如 Grid、StackLayout)类。可以为视图(例如标签、按钮)和布局类指定边距。

根据您的 HeaderContainerStyle 回到您的代码,我认为您正在尝试为 Label 创建样式,对吧?

要在 Xamarin.Forms 中执行此操作,您应该在 ResourceDictionary 中为特定的 TargetType 添加新的 create new Style

标签类的示例Style

<ResourceDictionary>
     <Style x:Key="labelRedStyle" TargetType="Label">
         <Setter Property="HorizontalOptions"Value="Center" />
         <Setter Property="VerticalOptions" Value="Center" />
         <Setter Property="FontSize" Value="15" />
         <Setter Property="TextColor" Value="Black" />
         <Setter Property="Margin" Value="15,10" />
     </Style>
<ResourceDicrionary>

以及示例用法:

<Grid>
    <Label Style="myLabelStyle" />
</Grid>

如果有帮助,请告诉我!等待更多问题:)

【讨论】:

    【解决方案2】:

    我假设这是 Xamarin.Forms 而不是 WPF,但如果您的 DataTemplate 被 ListView 使用,则它缺少 ViewCell

    <DataTemplate x:Key="HeaderContainerStyle">
        <ViewCell>
            <Label Margin="10" Text="{Binding}"/>
        </ViewCell>
    </DataTemplate>
    

    但是,如果您的DataTemplate 用于您自己创建的自定义控件,则可能不需要ViewCell,并且该控件的另一个问题可能是导致Margin 不起作用的原因。

    【讨论】:

    • 应该提到,这本来是我试过的,但它抛出了异常 System.ArgumentException: Value is an invalid value for HeaderTemplate Parameter name: value
    • 您是想将 DataTemplate 用作 DataTemplateSelector 的资源,还是只是想将其用作标签的样式?也许添加更多代码来展示您如何在页面上使用它会有所帮助。
    猜你喜欢
    • 1970-01-01
    • 2010-11-21
    • 1970-01-01
    • 2022-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多