Dot-Net
在 ViewModel 中獲取 WPF ListView.SelectedItems
有一些文章討論了為
ListView.SelectedItems大量程式碼添加數據綁定能力。在我的場景中,我不需要從 中設置它ViewModel,只需獲取選定的項目以便對它們執行操作,它是由命令觸發的,因此也不需要推送更新。是否有一個簡單的解決方案(就程式碼行而言),也許在程式碼隱藏中?只要不需要相互引用
View,我就可以使用程式碼隱藏。ViewModel我認為這是一個更通用的問題:“ VM 從按需查看數據的最佳實踐”,但我似乎找不到任何東西……
要獲得
SelectedItems僅在執行命令時,請使用CommandParameter並傳入ListView.SelectedItems.<ListBox x:Name="listbox" ItemsSource="{Binding StringList}" SelectionMode="Multiple"/> <Button Command="{Binding GetListItemsCommand}" CommandParameter="{Binding SelectedItems, ElementName=listbox}" Content="GetSelectedListBoxItems"/>
這可以使用互動觸發器來實現,如下所示
- 您將需要添加參考
Microsoft.Expression.Interactions System.Windows.Interactivity
將以下 xmlns 添加到您的 xaml
xmlns:i="http://schemas.microsoft.com/expression//2010/interactivity" xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"在您的 GridView 標記內添加下面的程式碼
<GridView x:Name="GridName"> <i:Interaction.Triggers> <i:EventTrigger EventName="SelectionChanged"> <i:InvokeCommandAction Command="{Binding Datacontext.SelectionChangedCommand, ElementName=YourUserControlName}" CommandParameter="{Binding SelectedItems, ElementName=GridName}" /> </i:EventTrigger> </i:Interaction.Triggers>ViewModel 中的程式碼在下面聲明屬性
public DelegateCommand<object> SelectionChangedCommand {get;set;}在 Viewmodel 的建構子中初始化命令如下
SelectionChangedCommand = new DelegateCommand<object> (items => { var itemList = (items as ObservableCollection<object>).Cast<YourDto>().ToList(); }