集合视图,选定项= "{Binding SelectedElement, Mode=TwoWay}"不起作用



我正在尝试绑定"SelectedItems;属性。但是TwoWay不起作用。

我可以将信息发送到我的视图,但不能将信息发送给我的ViewModel。

(所有其他投标都正确(

一些代码,在我的ViewModel中:

private ObservableCollection<Element> _selectedElement;
public ObservableCollection<Element> SelectedElement
{
get
{
return _selectedElement;
}
set
{
if (_selectedElement != value)
{
_selectedElement = value;
}
}
}

在我看来

<CollectionView  ItemsSource="{Binding Elements,Mode=TwoWay}" 
SelectionMode="Multiple"
SelectedItems="{Binding SelectedElement, Mode=TwoWay}">
<CollectionView.ItemTemplate>
<DataTemplate>
<StackLayout  Orientation="Horizontal" >

<StackLayout   Padding="15,10" Orientation="Horizontal" >
<Label Text="{Binding Libelle}" VerticalOptions="Center" />
<Label Text="{Binding Code}" VerticalOptions="Center" />
</StackLayout>

<StackLayout HorizontalOptions="EndAndExpand" VerticalOptions="Center" >
<ImageButton Source="{Binding ImgFavori}"
BackgroundColor="Transparent"
Command="{Binding Path=BindingContext.ManageFavCommand, Source={x:Reference CurrentView}}"
CommandParameter="{Binding .}"
WidthRequest="75" 
VerticalOptions="Fill"/>
</StackLayout>

</StackLayout>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>

当我使用ViewModel像这样操作视图时:

private async void ClearCollection()
{
SelectedElement = null;
}

这就是工作。

但当我试图在智能手机上选择某一行时,我从未输入SelectedElement的setter。

我正在使用Xamarin.Forms 5.0.0.2196

谢谢你帮我。

在你的帮助下,我发现了我的问题。

我不需要使用SelectionChangedCommand(他工作,但我不需要这个事件,我只需要数据(

但在尝试你的答案时,我添加了以下内容:

SelectionChangedCommandParameter="{Binding .}

现在我的IList SelectedElement已经在我的视图中选择了数据!

谢谢你帮我。

需要两个更改:

  1. 绑定属性(SelectedElement(的类型必须与CollectionView属性(SelectedItems(的类型匹配。XF Doc表示型号为IList<object>

  2. 解析绑定时(页面已加载;BindingContext已设置(,绑定属性(如果类型正确(将设置为SelectedItems列表。它一开始是一个空列表。随着选择的更改,列表的内容也会更改但是list对象本身是同一个对象,所以setter再也不会被调用

那么你如何看待变化呢?通过SelectionChangedCommandSelectionChanged事件。


使用SelectionChangedCommand:

添加到CollectionView XAML:

<CollectionView ... SelectionChangedCommand="{Binding SelectionChangedCommand}" ...>

添加到视图模型(BindingContext(:

// There's no point in customizing this setter, because it won't get called when you want it to.
public IList<object> SelectedElement { get; set; }
// in constructor:
SelectionChangedCommand = new Command(SelectionChanged);
public Command SelectionChangedCommand { get; set; }
private void SelectionChanged(object obj)
{
if (SelectedElement != null && SelectedElement.Count > 0) {
var element = SelectedElement[0] as Element;
...
}
}