【发布时间】:2020-06-08 14:00:18
【问题描述】:
尝试通过单击按钮调用命令时遇到问题,这是我的代码,请帮助 后记,如果我把按钮从collectionView上移开,命令就起作用了。 该命令的名称是 ButtonCommand ,我想我需要更多的参数,帮助。
MaingPage.Xaml
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
x:Class="XamarinCollectionView.MainPage"
xmlns:viewModels="clr-namespace:PruebaAppMap.ViewModels"
xmlns:Models="clr-namespace:PruebaAppMap.Models"
x:DataType="viewModels:MainPageViewModel"
BackgroundColor="#2471A3">
<CollectionView ItemsSource="{Binding Products}">
<CollectionView.ItemTemplate>
<DataTemplate x:DataType="Models:Product">
<Frame
Padding="5"
CornerRadius="5"
IsClippedToBounds="False">
<Grid HeightRequest="100">
<Grid.ColumnDefinitions >
<ColumnDefinition Width=".3*"/>
<ColumnDefinition Width=".7*"/>
<ColumnDefinition Width=".4*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height=".5*"/>
<RowDefinition Height=".5*"/>
<RowDefinition Height=".7*"/>
</Grid.RowDefinitions>
<Label Grid.Column="1" FontAttributes="Bold" FontSize="Large" VerticalOptions="Center" Text="{Binding Name}"/>
<Label Grid.Column="1" Grid.Row="1" FontSize="Medium" Text="{Binding Price,StringFormat='{0:C}'}"/>
<Button Grid.Column="3" Grid.RowSpan="2" Grid.Row="1" x:DataType="viewModels:MainPageViewModel" Text="Click me!" CommandParameter="{Binding}" Command="{Binding ButtonCommand}"/>
</Grid>
</Frame>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
视图模型--MainPageViewModel
namespace PruebaAppMap.ViewModels{
public class MainPageViewModel
{
public ObservableCollection<Product> Products { get; set; }
public ICommand ButtonCommand { get; set; }
public MainPageViewModel()
{
Products = new ObservableCollection<Product>
{
new Product
{
Name="Yogurt",
Price=5.50m,
Image="yogurt.png",
hasOffer=false
},
};
ButtonCommand = new Command(async () => await buton());
}
public async Task buton()
{
await App.Current.MainPage.DisplayAlert("Button pressed", "button was pressed", "ok");
}}
}
【问题讨论】:
-
DataTemplate 中元素的 BindingContext 是 Product 的一个实例。
ButtonCommand没有为 Product 定义。 -
我从来没有对 Xamarin 做过任何事情,但在 WPF 中你会做类似
Command="{Binding ButtonCommand, RelativeSource={RelativeSource AncestorType=ContentPage}}"的事情。类似的东西可能在这里起作用。 -
我是 xamarin 的新手,不知道该怎么做
-
有许多示例将向您展示如何在绑定中引用备用源
-
我的回答对你有用吗?
标签: c# xamarin.forms