Editable DataGrid in WPF with Tab + Enter support, using MVVM
I've got a datagrid containing "part" objects, consisting of a handful of template columns. The majority of the fields are read-only, a few of them are editable. The tab key needs to cycle between the editable fields; I seem to have that part worked out. The catch is this... when the user enters a part number into the first textbox, he or she can press TAB or ENTER to lookup the part number and receive a message saying the number is invalid in case of failure, or have that part's information added to the grid in case of success.
Here is my problem- if they use TAB, the 'quantity' textbox needs to become focused, while a new, empty row is added below. If they use the ENTER key, an empty row needs to be added and the new 'part number' textbox needs to be focused. I am unable to find a way to focus the textboxes in my viewmodel. I can do it using some events in codebehind, but I can't find a way to add an unfocused row with TAB, and a focused row with ENTER. Setting CanUserAddRows to true doesn't even seem to function properly, to this point I've been manually adding rows on successful part lookup, which is also causing issues. How can I handle the slightly different tab/enter cases? I potentially also need to able to address lostFocus on the part number box, in cas开发者_如何学Pythone they click another control after entering the number.
Setting focus should be done in the code-behind of the View, not the ViewModel, because a concept like focus is view-specific
Adding a new row with the Tab key should be done in the ViewModel. I would register a command on your KeyDown event that goes to your ViewModel and passes it the key that was pressed. The ViewModel would check that the key was the Tab key, and if so add a new row.
I like using this code from this site for attaching Commands
to Events
, but there are many other implementations of this functionality around so use whatever you're comfortable with.
精彩评论