您好我想使用BindingContext
属性根据特定条件将不同的ViewCell
绑定到Listview
这是Xaml
<ListView>
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell BindingContext="??">//What do I do here?
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
以下是ViewCells的类
public class textViewCellNoContextActions : ViewCell
{
public textViewCellNoContextActions()
{
StackLayout layout = new StackLayout();
layout.Padding = new Thickness(15, 0);
Label label = new Label();
label.SetBinding(Label.TextProperty, "ListItemTitle");
layout.Children.Add(label);
View = layout;
}
}
public class textViewCellWithContextActions : ViewCell
{
public textViewCellWithContextActions()
{
StackLayout layout = new StackLayout();
layout.Padding = new Thickness(15, 0);
Label label = new Label();
label.SetBinding(Label.TextProperty, "ListItemTitle");
layout.Children.Add(label);
var moreAction = new MenuItem { Text = "More" };
moreAction.SetBinding(MenuItem.CommandParameterProperty, new Binding("."));
moreAction.Clicked += OnMore;
var deleteAction = new MenuItem { Text = "Delete", IsDestructive = true }; // red background
deleteAction.SetBinding(MenuItem.CommandParameterProperty, new Binding("."));
deleteAction.Clicked += OnDelete;
this.ContextActions.Add(moreAction);
this.ContextActions.Add(deleteAction);
View = layout;
}
在我的ViewModel
中,我想决定绑定哪个ViewCell
。我该如何实现这一目标?
我是否还需要使用BindingContextChanged
?
答案 0 :(得分:2)
您想要使用DataTemplateSelector
- 您并没有真正更改每个单元格的Binding上下文,就像更改使用的可视单元格一样。 ListView本身将控制那些绑定上下文。
https://blog.xamarin.com/customizing-list-view-cells-xamarin-forms-datatemplateselector/
答案 1 :(得分:2)
对于我想要实现的目标,我做了以下......
在XAML中
<ViewCell BindingContextChanged="OnBindingContextChanged">
在背后的代码中
private void OnBindingContextChanged(object sender, EventArgs e)
{
base.OnBindingContextChanged();
if (BindingContext == null)
return;
ViewCell theViewCell = ((ViewCell)sender);
var item = theViewCell.BindingContext as ListItemModel;
theViewCell.ContextActions.Clear();
if (item != null)
{
if (item.ListItemType == ListItemTypeEnum.FavoritePlaces
|| item.ListItemType == ListItemTypeEnum.FavoritePeople)
{
theViewCell.ContextActions.Add(new MenuItem()
{
Text = "Delete"
});
}
}
}
根据我们正在处理的列表项类型,我们可以决定上下文操作的放置位置
答案 2 :(得分:0)
您可以直接使用ViewCell元素中的属性,如下所示。 ViewCell不需要BindingContext
。
<ListView ItemsSource="{Binding Attachments}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout>
<Label Text="{Binding Name}" />
<Image Source="{Binding FilePath}"/>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
只需确保不要将ViewCell.View
用作ViewCell
的子元素。
即使您有ViewCell
的子类或自定义类,此方法也应有效。