自定义控件,例如带有Xamarin.Forms的StackLayout [英] Custom control like StackLayout with Xamarin.Forms
问题描述
我只想用Xamarin.Forms创建一个自定义控件。此自定义控件应在xaml中获取视图的数组/列表(例如 Stacklayout
)。
I just want to create a custom control with Xamarin.Forms. This custom control should take an array/list of views in the xaml (like the Stacklayout
, for example).
我的XAML看起来像这样:
My XAML Looks like this:
<controls:MyLayout>
<ContentView BackgroundColor="Green">
<Label Text="Test 1" />
</ContentView>
<ContentView BackgroundColor="Red">
<Label Text="Test 1" />
</ContentView>
</controls:MyLayout>
以及 MyLayout
的类:
[ContentProperty("Children")]
public class MyLayout: ScrollView, IViewContainer<View>
{
public IList<View> Children { get; set; }
// And some more properties and methods ...
}
但是当我编译它并在我的Android手机上运行它时,出现以下错误:
But when I compile this and run it on my Android phone, I get the following error:
已引发异常调用的目标。 --->
Xamarin.Forms.Xaml.XamlParseException:位置29:8。无法分配
属性子项: Xamarin.Forms.ContentView
和 System.Collections.Generic.IList`1 [Xamarin.Forms.View]之间的类型不匹配
Exception has been thrown by the target of an invocation. ---> Xamarin.Forms.Xaml.XamlParseException: Position 29:8. Cannot assign property "Children": type mismatch between "Xamarin.Forms.ContentView" and "System.Collections.Generic.IList`1[Xamarin.Forms.View]"
我该如何解决?我缺少什么?
How can I solve this? What am I missing?
推荐答案
您的财产孩子必须只能获得访问者。我记得这也是一个面临的问题。
Your property Children must to have only get accessor. As I remember this was an issue a faced too. And also that list must be initialized.
[ContentProperty("Children")]
public class MyLayout: ScrollView, IViewContainer<View>
{
public IList<View> Children { get; } = new List<View>();
// And some more properties and methods ...
}
I `d宁愿这样
[ContentProperty(nameof(Children))]
public class MyLayout: ScrollView, IViewContainer<View>
{
private List<View> _children;
public IList<View> Children => _children;
public MyLayout()
{
_children = new List<View>();
}
// And some more properties and methods ...
}
甚至使用ObservableCollection<>而是简单的List<>。 ObservableCollection可以帮助您观察集合何时发生更改,它可以帮助您何时布局的内容子级在布局中添加或删除
Or even use ObservableCollection<> instead simple List<>. ObservableCollection can help you to observe when collection changes an it can help you when layout`s content children adds or removes from layout
这篇关于自定义控件,例如带有Xamarin.Forms的StackLayout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!