列表视图选择“活动”物品
我有一个 < code>ListView 绑定到 ObservableCollection
(Listview.ItemsSource
)。列表视图显示了几个绑定到可观察集合中对象的属性的文本框。
我希望具有以下功能:当用户将焦点集中在文本框中时,应选择列表视图中的相应项目。
我已经尝试过 ContainerFromElement、ContainerFromItem 等,但无法让这个“简单”功能发挥作用。
任何想法...
Possible Duplicate:
Select ListBoxItem if TextBox in ItemTemplate gets focus
I have a ListView
bound to an ObservableCollection
(Listview.ItemsSource
). The listview presents several textboxes that are bound to properties of the objects in the observable collection.
I would like to have the following functionality: when a user focusses a textbox the corresponding item in the listview should get selected.
I have tried things with ContainerFromElement, ContainerFromItem, etc. but can't get this "simple" functionality to work.
Any ideas...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这里的技巧是使用
ItemContainerStyle
上的IsKeyboardFocusWithin
属性:在这个例子中,我们只是简单地声明,只要该项目内的控件包含键盘焦点。
注意:反方向则不起作用;选择列表中的特定项目不会自动将焦点集中到所包含的
TextBox
编辑以响应评论
正如 Joep 指出的,这将意味着失去键盘焦点(这将当
TextBox
之外的控件获得焦点时发生)将导致IsSelected
属性重置为 false。您可以通过用触发器输入操作替换Style
setter 来解决此问题,这样可以防止触发器不再有效时撤消更改。为了使其与前面的示例以相同的方式工作,您需要将
ListView
的SelectionMode
显式设置为Single
;否则,可以一次选择多个项目。The trick here is to use the
IsKeyboardFocusWithin
property on theItemContainerStyle
:In this example we are simply stating that
IsSelected
should be set to true whenever a control within that item contains the keyboard focus.Note: this does not work in the opposite direction; selecting a particular item in the list will not automatically give focus to the contained
TextBox
Edit in response to comments
As Joep pointed out, this will mean that losing keyboard focus (which will happen when a control besides the
TextBox
gains focus) will cause theIsSelected
property to be reset to false. You can work around this by replacing theStyle
setter with an trigger enter action, which prevents the change from being undone when the trigger is no longer valid.For this to work in the same way as the previous example you will need to explicitly set the
SelectionMode
for theListView
toSingle
; otherwise, multiple items can become selected at once.MVVM 方式会向 ViewModel 添加额外的属性来表示所关注的属性。
例如,如果 ViewModel 有一个属性 Name,则添加一个属性 IsNameFocussed,如果它有一个属性 Address,则添加一个属性 IsAddressFocussed。
然后将 DataTemplate 中的相应控件绑定到 Is...Focussed 属性以突出显示它。
剩下的就是在文本框的 GotFocus 和 LostFocus 事件中设置 Is...Focused 属性。 (我宁愿绑定到一个焦点属性,但它不在那里......)
The MVVM way would add extra properties to the ViewModel representing the properties that are focussed.
E.g., if the ViewModel has a property Name add a property IsNameFocussed, if it has a property Address, add a property IsAddressFocussed.
Then bind the appropriate control in the DataTemplate to the Is...Focussed property to highlight it.
All that is left is setting the Is...Focussed property in the GotFocus and LostFocus events of the textboxes. (I'd rather bind to a Focussed Property but it's not there...)