如何在绑定到画布的集合中找到具有特定值的项目
我已经用谷歌搜索了一下这个问题,但没有得到任何真正的答案。可能是因为我的问题可能有点神秘。假设
我有一个包含一堆模型的 ObservableCollectionItemsSource
绑定到 ObservableCollection
。这很好用。 SomeModel 绑定到 SomeView,这是一个 UserControl。
现在,当此视图获得焦点时,或者当我将鼠标放在它上面时,我希望将其标记为“选定”。不知何故,我希望在保存画布的窗口后面的代码中有一个属性,我可以在其中始终获取所选项目。
我一直在考虑使用 BindingList 而不是 ObservableCollection
,并且当模型上的 IsSelected
属性发生更改时,方法将提取从列表中选择的项目。但这似乎有点影响性能,因为我会收到有关项目的所有更改的通知。
我怎样才能做到这一点?
I've been Google'ing a bit around for this, but without getting any real answer. Probably because my question might be a bit cryptic. Here goes:
Lets say i have an ObservableCollection<SomeModel>
containing a bunch of models. I then add the corresponding Views to a Canvas. Specifying this in the resources of the Window, and then bind the Canvas' ItemsSource
to the ObservableCollection<SomeModel>
. This works fine.
SomeModel is bound to SomeView, this is a UserControl.
Now, when this View gets focus, or when I MouseDown on it, I would like to have it marked as "Selected". Somehow, i would like to have a property in the codebehind to the Window holding my Canvas, where i can always get the selected item.
I've been thinking of having a BindingList instead of the ObservableCollection
, and when an IsSelected
property on the model changes, then a method will extract the selected item from the list. But this seems to be a bit of a performance killer, as i will be notified on all changes to the items.
How can I accomplish this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
有多种方法可以解决这个问题。但最简单的方法可能是使用 ListBox 并绑定到它。 ListBox 具有可绑定的 ItemsSource 和 SelectedItem 属性,该属性具有当前在其中选定的项目。如果您想在 .cs 文件后面的代码中执行某些操作,它还会在选择更改时调用 SelectionChanged 事件。
我建议将 ObservableCollection 保留在视图模型中,以忠于 MVVM。
如果 ListBox 的样式或位置不适合您,则将模板覆盖为更适合您需求的内容。
如果上述方法对您不起作用,您可以查看一种行为,但最好保持简单。
更新
这就是构建视图的方式。请注意,ItemsPanel 属性绑定到 UserControl.Resources 部分中定义的 ItemsPanelTemplate,该部分指定要放置项目的 Canvas。
关于视图模型
应该注意的是,Canvas 本身没有任何逻辑让用户在运行时在其上移动控件。
There are multiple ways you could solve this. But probably the simplest it to work with a ListBox and bind to it. ListBox as it has bindable ItemsSource and a SelectedItem property that has the item that is currently selected in it. It also calls the SelectionChanged event when the selection changes if you want to do something in the code behind .cs file.
I would recommend keeping the ObservableCollection in your View Model to keep true to MVVM.
If the style or placement of ListBox does not suit your override the template to something that suits your needs better.
You could look at a behaviour if the above doesn't work for you but best to keep it simple.
UPDATE
This is how you would build the view. Note the ItemsPanel attribute is bound to a defined ItemsPanelTemplate in the UserControl.Resources section which specifies a Canvas to put the items on.
On the View Model
It should be noted though that Canvas itself does not have any logic to let the user move controls around on it at runtime.