我有一个带有自定义ViewCell
的列表视图,该列表具有一个Label
和一个TapGestureRecognizer
,我想在 Parent BindingContext中触发它。该视图单元绑定到“ Something”视图模型,SomeThing视图模型是SomethingBigger视图模型的一部分。
public class CustomViewCell : ViewCell
{
#region bindable properties
public static readonly BindableProperty ToggleCommandProperty =
BindableProperty.Create(nameof(ToggleCommand), typeof(Command), typeof(CustomViewCell), null);
public ICommand ToggleCommand
{
get { return (ICommand)GetValue(ToggleCommandProperty); }
set { SetValue(ToggleProperty, value); }
}
#endregion
public CustomViewCell
{
Grid grid = new Grid
{
ColumnSpacing = 3,
RowSpacing = 0
};
//..........
// adding other elements here
//..........
var addLabel = new Label
{
Text = "+ Add",
FontSize = 11,
WidthRequest = 40,
Margin = new Thickness(0, 0, 0, 5),
HorizontalOptions = LayoutOptions.FillAndExpand,
VerticalOptions = LayoutOptions.FillAndExpand,
VerticalTextAlignment = TextAlignment.Center,
HorizontalTextAlignment = TextAlignment.Center
};
addLabel.GestureRecognizers.Add(new TapGestureRecognizer
{
Command = ToggleCommand,
CommandParameter = BindingContext
});
grid.Children.Add(addLabel, 7, 1);
Grid.SetRowSpan(addLabel, 2);
View = grid;
}
}
SomethingBiggerViewModel
,其中包含在点击标签时应执行的命令:
public class SomethingBiggerViewModel
{
public ICommand ToggleCommand { get; set; }
public SomethingBiggerViewModel()
{
ToggleCommand = new Command<SomethingViewModel>(async (something) => await ExecuteToggleCommand(something));
}
async Task ExecuteToggleCommand(SomethingViewModel something)
{
await _pageService.DisplayAlert("title", "item clicked " + something.Name, "Cancel");
}
}
并在页面中:
<ListView Grid.Row="3"
VerticalOptions="FillAndExpand"
CachingStrategy="RecycleElement"
x:Name="linesListView"
RowHeight="{Binding LineRowHeight}"
ItemsSource="{Binding Lines}"
SeparatorColor="#bfbfbf">
<ListView.ItemTemplate>
<DataTemplate>
<views:CustomViewCell ToggleCommand="{Binding Source={x:Reference ThePage}, Path=BindingContext.ToggleCommand}" />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
上面的代码可以编译,但是当我运行它时,它给我一个错误,“它仍然可以正常工作”,说“ SomethingViewModel”没有“ ToggleCommand”。
该怎么做?