【发布时间】:2021-08-03 21:07:39
【问题描述】:
所以我有一个 xamarin 表单应用程序,目前仅针对 android 实现。我正在尝试实现一个点击事件。当被点击时,虽然这永远不会命中 ViewModel 中的命令。我不确定我的代码是否有问题,或者我只是执行错误。
ViewModel 代码:
private RelayCommand<object> _OnClickableLabel;
public RelayCommand<object> OnClickableLabel
{
get { return _OnClickableLabel ?? (_OnClickableLabel = new RelayCommand<object>((currentObject) => Test(currentObject))); }
}
private void Test(object currentObject)
{
Application.Current.MainPage.DisplayAlert("Alert", "were going down cap", "OK");
}
页面 Xaml:
<ListView Grid.Row="1" ItemsSource="{Binding Notifications}" RowHeight="100">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Orientation="Vertical" BackgroundColor="{Binding BackgroundColor}">
<StackLayout.GestureRecognizers>
<TapGestureRecognizer Command="{Binding OnClickableLabel }" />
</StackLayout.GestureRecognizers>
<Label FontSize="Large" Text="{Binding Title}"></Label>
<Label FontSize="Small" Text="{Binding Text}"></Label>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
我已经使用页面的 cs 代码中的方法对其进行了测试,效果很好,但它必须在 ViewModel 中实现,因为它会影响该数据。
【问题讨论】:
-
您的命令在基础虚拟机上,但
ListView中每一行的BindingContext是一个单独的Notification对象,而不是整个虚拟机。您可以使用relative binding 来解决此问题 -
不知道,对 Xamarin 来说很新。我假设我使用的是 AncestorType 版本的 relativeSource?我在哪里可以确定 AncestorType 应该是什么类型?将 ViewModel 放在那里似乎不起作用。
-
另一种解决方法可能是为您的页面命名,例如
x:Name="this",然后在绑定上设置源,例如:Command="{Binding OnClickableLabel, Source={x:Reference this} }"
标签: c# xamarin xamarin.forms mvvm xamarin.android