【问题标题】:Bindable property return only default value可绑定属性仅返回默认值
【发布时间】:2017-02-06 04:54:35
【问题描述】:

我想在 xamarin.forms 中创建用户控件(用户视图)。我的控件有一个属性。控制选择要添加到页面的元素(条目或标签)。为此,我使用 BindableProperty,但它只返回默认值。不明白哪里错了?

这里是我的用户控制代码:

 public partial class UserView : ContentView
{
    public UserView()
    {
        InitializeComponent();
        StackLayout stackLayout = new StackLayout();
        if (TypeElement == "label")                              //TypeElement return only "default value"
            stackLayout.Children.Add(new Label { Text = "LABEL" });
        else
            stackLayout.Children.Add(new Entry { Text = "ENTRY" });

        Content = stackLayout;
    }

    public static readonly BindableProperty TypeProperty = BindableProperty.CreateAttached("TypeElement", typeof(string), typeof(UserView), "default value");

    public string TypeElement
    {
        get
        {
            return (string)GetValue(TypeProperty);
        }
        set
        {
            SetValue(TypeProperty, value);
        }
    }
}

这里我在页面上使用我的控件:

【问题讨论】:

    标签: c# xamarin.forms


    【解决方案1】:

    你的 TypeElement 属性在构造函数完成后被设置,你应该注意这个属性什么时候改变,然后做你需要做的事情,例如:

    public static readonly BindableProperty TypeProperty = BindableProperty.CreateAttached("TypeElement", typeof(string), typeof(UserView), "default value", propertyChanged:OnTypeElementChanged);
    
    private static void OnTypeElementChanged(BindableObject bindable, object oldValue, object newValue)
    {
        var userView = bindable as UserView;
        StackLayout stackLayout = new StackLayout();
        if (userView.TypeElement == "label")                              //TypeElement return only "default value"
            stackLayout.Children.Add(new Label { Text = "LABEL" });
        else
            stackLayout.Children.Add(new Entry { Text = "ENTRY" });
    
        userView.Content = stackLayout;
    }
    

    我已经对此进行了测试并且它有效,但是关于您的实现有几件事让我感到困惑,例如为什么您使用附加属性而不是常规可绑定属性,以及为什么您似乎有 XAML如果您只是要替换内容,则与 UserView 关联的文件。

    【讨论】:

    • 非常感谢您的回答。你帮了我很大的忙。
    • 关于我的问题。我尝试创建具有某些属性的用户控件,例如“CountTextBox”、“CountLabel”等。这个属性我要填写XAML,然后得到复杂的控制。我的目标 - 一些“动态”控制。
    猜你喜欢
    • 1970-01-01
    • 2016-10-07
    • 2019-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-01
    • 1970-01-01
    相关资源
    最近更新 更多