如何定义可从Xaml访问的构造函数参数 [英] How to define an constructor argument accessible from Xaml
问题描述
Xamarin的ListView
定义了一个1参数的构造函数,如下所示:
Xamarin's ListView
defines a 1-argument constructor as follows:
public ListView([Parameter("CachingStrategy")] ListViewCachingStrategy cachingStrategy)
结果,可以在Xaml中使用CachingStrategy
:
As a result, CachingStrategy
can be used in Xaml:
<ListView CachingStrategy="RecycleElement" .../>
我想知道如何做同样的事情.由于ParameterAttribute
是Xamarin.Forms的内部代码,因此以下代码无法编译:
I'm wondering how I can do the same thing. The following code, as is, does not compile because ParameterAttribute
is internal to Xamarin.Forms:
public ItemListControl([Parameter("IsReadOnly")] bool isReadOnly)
我从Xamarin.Forms复制了类ParameterAttribute
,并进行了上述编译,但对Xaml处理没有影响.这是课程,供参考:
I copied class ParameterAttribute
from Xamarin.Forms, and the above compiled, but had no effect on Xaml processing. Here is the class, for reference:
[AttributeUsage(AttributeTargets.Parameter)]
internal sealed class ParameterAttribute : Attribute
{
public ParameterAttribute(string name)
{
Name = name;
}
public string Name { get; }
}
有什么我想念的吗?
推荐答案
为了简化操作,我建议创建一个 x:Arguments
来将参数传递给构造函数:
To make things simpler, I would recommend creating a BindableProperty
for IsReadOnly
. But you can always use x:Arguments
to pass in parameters to constructor:
<local:ItemListControl ...>
<x:Arguments>
<x:Boolean>true</x:Boolean>
</x:Arguments>
</local:ItemListControl>
编辑-1
There is one hack that you can use - (I wouldn't recommend as this could change anytime with an update in XAMLC compilation) - but you can make sure to keep the namespace same as the one used internally while defining the parameter attribute.
namespace Xamarin.Forms
{
[AttributeUsage(AttributeTargets.Parameter)]
internal sealed class ParameterAttribute : Attribute
{
public ParameterAttribute(string name)
{
Name = name;
}
public string Name { get; }
}
}
XAML的用法如下:
And XAML usage would look like:
<local:ItemListControl IsReadOnly="true" .. />
编辑-2 仅当将 XAMLCompilation 应用于主机控件时,此hack才起作用/page.
EDIT - 2 This hack only seems to work if XAMLCompilation is applied to host control/page.
这篇关于如何定义可从Xaml访问的构造函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!