[英]CollectionView, SelectedItems="{Binding SelectedElement, Mode=TwoWay}" Didn't work
我试图在我的视图和我的 ViewModel 之间绑定我的 CollectionView 的“SelectedItems”属性。 但是TwoWay没有用。
我可以向我的 View 发送信息,但我无法向我的 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
谢谢帮助我。
您是否尝试过放置 INotifyPropertyChanged? https://www.c-sharpcorner.com/article/use-inotifypropertychanged-interface-in-wpf-mvvm/
需要做两个改动:
类型结合的特性(的SelectedElement
)必须与的CollectionView属性(类型相匹配SelectedItems
)。 XF Doc说类型是IList<object>
。
当绑定被解析(页面被加载;BindingContext 设置)时,您的绑定属性(如果类型正确)将被设置为 SelectedItems 列表。 它从一个空列表开始。 随着选择的改变,列表的内容也会改变。 但是列表对象本身是同一个对象,所以 setter 永远不会被再次调用。
那么你怎么看变化呢? 通过SelectionChangedCommand
或SelectionChanged
事件。
使用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;
...
}
}
在您的帮助下,我发现了我的问题。
我不需要使用 SelectionChangedCommand (他工作,但我不需要这个事件,我只需要数据)
但是尝试你的答案,我补充说:
SelectionChangedCommandParameter="{Binding .}
现在我的 IList SelectedElement 在我的视图中选择了数据!
谢谢帮助我。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.