【发布时间】:2021-04-02 19:17:32
【问题描述】:
我在弄清楚如何从我的 XAML 而不是我的代码中正确绑定自定义事件处理程序时遇到了一些困难。在我后面的代码中,我目前在我的父代码后面有这个:
this.stepBar.Callback = SetViewForStep;
这很好,它会在我的自定义控件中正确设置回调事件处理程序,定义如下:
public static readonly BindableProperty CallbackProperty = BindableProperty.Create(nameof(Callback), typeof(EventHandler), typeof(StepProgressBarControl), null);
public EventHandler Callback {
get {
return (EventHandler)GetValue(CallbackProperty);
} set {
SetValue(CallbackProperty, value);
}
}
但是,我希望能够完全在 XAML 中定义它,就像在按钮上定义 Click 事件一样。
<StackLayout HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand"
Padding="20" Spacing="20">
<customcontrols:StepProgressBarControl
StepColor="LightPink"
Steps="5"
Callback="SetViewForStep"
StepSelected="{Binding SelectedStep}" x:Name="stepBar" />
<Label
Text="{Binding SelectedStep, StringFormat='The Step Selected is {0}'}"
FontAttributes="Bold"
FontSize="Large"
HorizontalOptions="Center"
VerticalOptions="CenterAndExpand" />
</StackLayout>
但是,如果我在 XAML 中定义它并尝试运行它,我会收到 Error XFC0009 No property, BindableProperty, or event found for "Callback", or mismatching type between value and property. 的编译错误
如何创建一个 EventHandler 以便我可以在我的 xaml.cs 中定义其功能,就像为按钮或任何其他具有公开 EventHandler 属性的内置控件定义单击事件一样?
【问题讨论】:
-
我将 caliburn.micro 用于 MVVM。触发事件时,您可以轻松地在视图模型中执行函数。它还使得绑定到大多数控件就像在 ViewModel 中将其命名为属性或方法一样简单。即,按下时名为 run 的按钮将尝试在 ViewModel 中执行名为 run 的方法。
标签: c# xamarin xamarin.forms