将ObservableCollection绑定到ListBox的

时间:2015-08-19 18:58:04

标签: c# wpf mvvm

经过数小时和数小时的Google搜索后,我仍然无法找到一个简单的解决方案,可以ObservableCollection模式将ListBox绑定到TwoWay模式的ListBox ... / p>

我所拥有的非常简单:SelectionMode="Multiple" ObservableCollection<Contact>SelectedContacts ListBox。我希望这两个受到约束。当然,我的ItemsSource="{Binding Contacts}"ObservableCollection,这是联系人的另一个IsSelected

现在我真的不能在我的Contact项目上使用class SomeClass<T> { init?(v: [String: AnyObject]) { if v["k"] is T { print("called if AnyObject is of type T") } else { print("called if AnyObject is not of type T") return nil } } } if let _ = SomeClass<Int>(v: ["k": 4]) { print("called") } if let _ = SomeClass<Int?>(v: ["k": 4]) { print("not called") } bool,我就是不能。

谢谢!

3 个答案:

答案 0 :(得分:3)

不是简单的解决方案。您无法绑定SelectedItems

最佳解决方案是将Contact项选择到具有IsSelected属性的视图模型对象中,绑定到该项,然后针对主OC运行查询当您需要获取所选项目集合时。

由于您说您不能/不会这样做,下一个最佳解决方案可能是在代码隐藏中处理SelectionChanged并从那里手动更新VM集合。

答案 1 :(得分:1)

由于SelectedItems不是DependencyProperty,因此不允许使用绑定

但是有一个解决方案,请看看这篇文章: http://blogs.microsoft.co.il/miziel/2014/05/02/wpf-binding-listbox-selecteditems-attached-property-vs-style/

答案 2 :(得分:0)

另一个选择是不跟踪ViewModel中的所选项目。相反,当您尝试执行某些操作时,请从UI将其作为CommandParameter传递。

示例:

<ListBox x:Name="MyListBox" 
         ItemsSource="{Binding SomeCollection}" />
<Button Command="{Binding SomeCommand}" 
        CommandParameters="{Binding SelectedItems, ElementName=MyListBox}" />