【发布时间】:2020-06-19 09:13:45
【问题描述】:
xamarin 新手。如何从可绑定的 flexlayout 中选择项目,类似于从列表视图中选择项目?谢谢大家。
ListView 运行良好,但我一直在尝试从 Listview 转换为 FlexLayout。
这是来自列表视图的逻辑代码。不知道从哪里开始 flexlayout
async void TypeListSelected(object objector, SelectedItemChangedEventArgs eventor)
{
object type = eventor.SelectedItem;
if (type == null)
return;
await Navigation.PushAsync(new EntryPage(new EntryViewModel(type)));
TypesListView.SelectedItem = null;
}
这是带有新的 flex 布局和点击手势的 xaml 页面
<FlexLayout x:Name="FlexTypes"
Wrap="Wrap"
Direction="Row"
HorizontalOptions="FillAndExpand"
JustifyContent="SpaceEvenly"
BindableLayout.ItemsSource="{Binding TypesCollection}">
<BindableLayout.ItemTemplate>
<DataTemplate>
<StackLayout Padding="0, 0, 0, 25">
<Frame x:Name="FrameTypes" HasShadow="False"
WidthRequest="125"
BorderColor="#C0C0C0">
<Frame.GestureRecognizers>
<TapGestureRecognizer Tapped="TypeListSelected"></TapGestureRecognizer>
</Frame.GestureRecognizers>
<StackLayout x:Name="LayoutTypesList">
<Label>
<Label.FormattedText>
<FormattedString>
<Span FontSize="Subtitle" Text="{Binding Title}"
FontAttributes="Bold"></Span>
</FormattedString>
</Label.FormattedText>
</Label>
<Label FontSize="Small" Text="{Binding Version}"
TextColor="#LELELE"></Label>
<Label Text="{Binding Description}" FontSize="Body"
VerticalOptions="CenterAndExpand"></Label>
<Label FontSize="Caption"
VerticalOptions="CenterAndExpand"
TextColor="#COCOCO">
<Label.FormattedText>
<FormattedString>
<Span Text="{Binding fDepartment}"></Span>
<Span Text="{Binding pType}"></Span>
</FormattedString>
</Label.FormattedText>
</Label>
</StackLayout>
</Frame>
</StackLayout>
</DataTemplate>
</BindableLayout.ItemTemplate>
</FlexLayout>
这是我的视图模型
public ObservableCollection<TypeModel> TypesCollection { get; set; }
public Command LoadTypesCommand { get; set; }
public TypesViewModel()
{
Title = "Browse Types";
TypesCollection = new ObservableCollection<TypeModel>();
LoadTypesCommand = new Command(async () => await ExecuteLoadTypesCommand());
}
async Task ExecuteLoadTypesCommand()
{
if (IsBusy)
return;
IsBusy = true;
try
{
TypesCollection.Clear();
var api = await DataSource.GetTypesApi(true);
foreach (var i in api)
{
TypesCollection.Add(i);
}
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
finally
{
IsBusy = false;
}
}
【问题讨论】:
-
您可能需要将 TapGestureRecognizer 附加到您的模板中
-
我为框架设置了 TapGestureRecognizer。我需要把它移到别的地方吗?就像在数据模板上一样?
-
应该可以。但是
TypeListSelected的签名是错误的,Tapped事件只使用了一个通用的EventArgs参数。您需要使用发件人的BindingContext来获取所选项目。 -
哦,好的。我是否朝着正确的方向前进? async void TypeListSelected(object objector, EventArgs eventor) { var frame = (Frame)objector; type = frame.BindingContext // 做更多的事情 await Navigation.PushAsync(new EntryPage(new EntryViewModel(type)));\ }
-
我想是的。您应该将
BindingContext转换为正确的类型。
标签: listview xamarin mvvm model binding