如何定义可从 Xaml 访问的构造函数参数 [英] How to define an constructor argument accessible from Xaml
问题描述
Xamarin 的 ListView
定义了一个 1-argument 构造函数,如下所示:
Xamarin's ListView
defines a 1-argument constructor as follows:
public ListView([Parameter("CachingStrategy")] ListViewCachingStrategy cachingStrategy)
因此,CachingStrategy
可以在 Xaml 中使用:
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; }
}
有什么我遗漏的吗?
推荐答案
为了让事情更简单,我建议创建一个 BindableProperty
用于 IsReadOnly
.但您始终可以使用 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
您可以使用一种 hack -(我不建议这样做,因为这可能 在 XAMLC 编译中随更新随时更改) - 但您可以确保在定义参数属性时保持命名空间与内部使用的命名空间相同.
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此 hack 似乎仅在 XAMLCompilation 应用于主机控制时才有效/页.
EDIT - 2 This hack only seems to work if XAMLCompilation is applied to host control/page.
这篇关于如何定义可从 Xaml 访问的构造函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!