[英]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.