我想在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);
}
}
}
我在页面上使用我的控件:
答案 0 :(得分:2)
您的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关联的文件。