我创建了一个名为PINControl
的自定义视图,其中显示了具有可配置位数的PIN条目。
我想在我的ContentPage
中使用的XAML是
<local:PINControl x:Name="PIN"
PINLength="5"
PINCompleteCommand="{Binding CompletePIN}"
HorizontalOptions="CenterAndExpand" />
PINControl中的我的BindableProperties是:
public class PINControl : StackLayout
{
private const int LENGTH_DEFAULT = 4;
public static readonly BindableProperty PINLengthProp = BindableProperty.Create<PINControl, int> (c => c.PINLength, LENGTH_DEFAULT);
public static readonly BindableProperty PINCompleteCommandProp = BindableProperty.Create<PINControl, ICommand> (c => c.PINCompleteCommand, null);
public ICommand PINCompleteCommand {
get { return (ICommand)GetValue (PINCompleteCommandProp); }
set { SetValue (PINCompleteCommandProp, value); }
}
public int PINLength {
get { return (int)GetValue (PINLengthProp); }
set { SetValue (PINLengthProp, value); }
}
我的ViewModel包含
public ICommand CompletePIN { get; set; }
public PINViewModel ()
{
CompletePIN = new Command<string> ((pin) => {
var e = pin.ToString();
});
}
PINLength
似乎没有问题,但PINCompleteCommand
给出了以下错误:
无法分配属性“PINCompleteCommand”:“Xamarin.Forms.Binding”和“System.Windows.Input.ICommand”之间的类型不匹配
我无法找到解决此问题的方法。有人可以帮帮我吗?
答案 0 :(得分:4)
在命名BindableProperties时要遵循一个很好的做法,即命名为propertynameProperty
。
在您的情况下,当Xaml解析器遇到此指令时
PINCompleteCommand="{Binding CompletePIN}"
它首先尝试查找名为PINCompleteCommandProperty的公共静态BindableProperty,失败,然后查找名为PINCompleteCommand的普通属性,成功,并尝试将值(Binding
)分配给属性({{{ 1}})并生成您正在看到的消息。
修复你的BindableProperty命名,你应该没问题。
答案 1 :(得分:0)
不确定它是否适用于OP情况,但值得注意的是,如果ViewModel / BindingTo属性与BindableProperty名称相同并且绑定两者,则也会出现这种情况在一起。
例如。
CustomControl - &GT; PinLengthCommand / PinLengthCommandProperty
视图模型 - &GT; PinLengthCommand
只需在viewmodel上更改属性的名称,它就会运行正常。