【问题标题】:Can I combine a Xaml <Label> into a C# template that I use to create a Frame?我可以将 Xaml <Label> 组合到用于创建框架的 C# 模板中吗?
【发布时间】:2020-12-05 08:33:51
【问题描述】:

我有 XAML 代码,用于设置这样的框架和框架标题:

<Label Text="ABC" />
<t:ContentFrame>
   <Label Text="ABC" />
</t:ContentFrame>

对于ContentFrame,我在这里使用C#模板:

[Xamarin.Forms.ContentProperty("Contents")]
public class ContentFrame : CustomFrame
{
    StackLayout contentStack { get; } = new StackLayout()
    {
        Spacing = 0,
        Padding = new Thickness(0),
        Orientation = StackOrientation.Vertical
    };
    public IList<View> Contents { get => contentStack.Children; }

    public ContentFrame()
    {
        Content = contentStack;
        HasShadow = false;
        SetDynamicResource(BackgroundColorProperty, "ContentFrameBackgroundColor");
        SetDynamicResource(BorderColorProperty, "ContentFrameBorderColor");
        SetDynamicResource(CornerRadiusProperty, "ContentFrameCornerRadius");
    }
}

有没有一种方法可以将标题的设置结合到 ContentFrame 类中,这样可以实现相同的目的:

<t:ContentFrame Heading="ABC">
   <Label Text="ABC" />
</t:ContentFrame>

【问题讨论】:

    标签: c# xaml xamarin xamarin.forms bindableproperty


    【解决方案1】:

    为此,您需要Bindable property

    public class ContentFrame : CustomFrame
    {
    StackLayout contentStack { get; } = new StackLayout()
        {
            Spacing = 0,
            Padding = new Thickness(0),
            Orientation = StackOrientation.Vertical
        };
        public IList<View> Contents { get => contentStack.Children; }
        public static readonly BindableProperty HeadingProperty =
                BindableProperty.Create(nameof(Heading), typeof(string),
                typeof(ContentFrame), null, propertyChanged: OnHeadingChanged);
    
        public string Heading
        {
            get => (Heading)GetValue(HeadingProperty);
            set => SetValue(HeadingProperty, value);
        }
    
    static void OnHeadingChanged(BindableObject bindable, object oldValue, object newValue) {
    //whatever you want to handle
     }
    
        public ContentFrame()
        {
            Content = contentStack;
            HasShadow = false;
            SetDynamicResource(BackgroundColorProperty, "ContentFrameBackgroundColor");
            SetDynamicResource(BorderColorProperty, "ContentFrameBorderColor");
            SetDynamicResource(CornerRadiusProperty, "ContentFrameCornerRadius");
        }
    }
    

    如果您不需要InotifypropertyChanged,您可以删除OnHeadingChanged(也可以从BindableProperty.Create() 内部删除,如果需要,您可以添加以下声明。

    【讨论】:

    • 您能否在问题的 C# 代码中给出一个示例,以便我可以看到如何执行此操作的完整图片。谢谢
    • 我的意思是公共类 ContentFrame 的完整代码。我认为最好说清楚,以便其他人可以看到如何添加所需的内容。
    • 我认为它可能被否决了,因为您只是提供了一个 sn-p 代码并使用了......而不是添加实际需要的内容。如果您想添加完整的代码,我很乐意接受答案。谢谢
    • 很抱歉,您最初的问题并未阐明这一点,我会尝试。
    • 我添加了这个新问题stackoverflow.com/questions/65178643/…
    猜你喜欢
    • 2021-12-18
    • 2023-03-19
    • 1970-01-01
    • 2019-09-15
    • 1970-01-01
    • 1970-01-01
    • 2015-08-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多