Setting any of these properties in code does in fact select the row and give it some kind of focus but the behaviour is slightly different compared to when clicking on it.

It is however possible to select and focus a row in code and get the same behaviour as when using the mouse by accessing the visual user interface elements of the DataGrid control and calling the UIElement. Focus method on a particular System. DataGridCell object as described in this post. You can also select an individual cell using almost the same approach. The DataGrid control has a SelectionUnit property that decides whether rows, cells or both can be selected.

For you to be able to set the SelectedItem or SelectedIndex properties of the DataGrid without an exception being thrown, this property must be set to its default value of System. There is also a SelectionMode property that specifies whether only a single item or multiple items can be selected in the DataGrid and these two properties together defines the selection behaviour for the DataGrid control.

The visual tree in a WPF application describes the structure of all visual elements that are part of the user interface, i. The DataGrid control renders a System. DataGridRow object for each data object in its Item collection and a System. DataGridCell for each cell of each row. There is a built-in System. VisualTreeHelper class that provides functionality for enumerating the members of a visual tree and this one is very useful whenever you need programmatic access to any object in the visual tree.

The VisualTreeHelper class is for example used in the below generic method that recursively searches for a user interface element of a specific type among the descendants of a visual object of type System.

DependencyObject — this is the base class for all visual elements that adds support for dependency properties — that is passed to the method as a parameter. The specific type to search for is specified by the type argument for the method.

ItemContainerGenerator of the DataGrid control respectively. Each ItemsControl, such as the DataGrid control, has its own instance of an ItemContainerGenerator object which is exposed through a property with the same name:. Note that the ContainerFromIndex method of the ItemContainerGenerator object will return a null reference if the visual DataGridRow object for the data item has been virtualized away.

This means that the item container generation and associated layout computation for a data bound item is deferred until the item is visible and only a subset of the controls for the data bound items is displayed on the screen at the same time. As the user scrolls through the list, elements are added and removed from the visual tree. If you for example bind the DataGrid to a collection of a hundred Product objects, only the ones that are currently visible on the screen and a few more will actually be present in the visual tree.

You can bring a virtualized item into view by using the ScrollIntoView method of the DataGrid control as shown in the SelectRowByIndex method in the code snippet above. After the call to this method, you will be able to get the DataGridRow object for the item that was passed to the method as a parameter.

Once you have obtained a reference to the particular DataGridRow element for the data object or row index you want to focus, the next step is to use the generic FindVisualChild method to find the System.

Get the Selected column and row from DataGrid in WPF

DataGridCellsPresenter element in the visual tree.It works well from the View to View Model. You can find the list of selected rows using linq on the observablecollection of rowvm and you can set isselected on a row from a rowviewmodel or the window viewmodel containing that collection. You will also have to style the cells so they're transparent and the row background blue if you want to see them light up blue because setting the isselected from the viewmodel won't give a row focus.

The dependency property or behaviour must set the IsSelected property of the corresponding DataGridRow container for this to work. You better use a Blend behaviour to implement this.

A Blend behaviour provides a better way of encapsulating the functionality of a behaviour compared to an ordinary attached behaviour. Download the System. Creata a class that derives from System.

If you want the selected row to get highlighted the same way as when you select a row by clicking on it with the mouse you have some more work to do. Note that you may also have to take virtualized DataGridRow elements into consideration.

There is information about this in the blog post as well. Anyway, the above information should get you the idea and all necessary information required to solve your issue. Don't post several questions in the same thread. Ask a question.

Quick access. Search related threads. Remove From My Forums. Answered by:. Archived Forums. Sign in to vote. It is quite simple to do the same in the Code behind. Appreciate any help on this. Saturday, November 8, PM. I would usually add a public property IsSelected to a row viewmodel and twoway bind that.

HighlightBrushKey is that blue you see when you highlight a row. Sunday, November 9, AM. OnAttached ; this. OnDetaching ; if this.By using our site, you acknowledge that you have read and understand our Cookie PolicyPrivacy Policyand our Terms of Service. Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information.

In your code you can use the "SelectedItem" property to get current selected datagrid row. Else if you mean "checked" rows, you can query your observable collection:.

Learn more. Asked 8 years, 3 months ago. Active 8 years, 3 months ago. Viewed 15k times. I have a DataGrid with checkbox implemented on it using this code which I found on the internet. Please can you folks add a comment to question when you guys are downvoting. Then, they will know WHY their questions are downvoted. Active Oldest Votes. IsSelected. Sign up or log in Sign up using Google. Sign up using Facebook.

Sign up using Email and Password. Post as a guest Name. Email Required, but never shown. The Overflow Blog. Podcast Ben answers his first question on Stack Overflow.

The Overflow Bugs vs. Featured on Meta. Responding to the Lavender Letter and commitments moving forward. Related Hot Network Questions. Question feed. Stack Overflow works best with JavaScript enabled.It is pretty easy to work with, and it produces pretty good results. I put together a demo to document the basic operations that I will need to perform with the DataGrid on an upcoming project, and I thought I would share it with the CodeProject community.

In particular, I wanted to share my approach to drawing a drop-line on the grid while a row drag was in process.

How to programmatically select and focus a row or cell in a DataGrid in WPF

I think you will find it particularly helpful if you are trying to get a handle on MVVM, although even experienced hands will find the DataGrid discussion to be useful. As you will see in going through the article, MVVM heavily influences almost every aspect of working with the DataGrid. For many developers, including myself, it is simply the way that WPF is done. For the demo app, I needed a simple model with no natural order, so I borrowed the family grocery list from last Friday, and I made an object model out of that.

It is the sort of list that one might use to perform all of the DataGrid tasks listed above. I haven't included data persistence in the demo, since there are so many ways of doing that. Instead, I create the object model at runtime. When you start the demo, you will see a grocery list on a DataGrid. The grid has two columns:. I use a fairly conventional implementation of MVVM. Both patterns are approaches for moving business and control logic out of a UI the View.

In both, a coordinator class is placed between the UI and the domain model. The coordinator class communicates with the View, and it contains the business and control logic that otherwise would have gone into code-behind in the View.

However similar the two patterns may be, they are not the same. I personally draw the following distinction between the two patterns:. I believe that the MVC approach gives me greater flexibility to change the View, without causing unintended consequences in the ViewModel. In other words, I believe it does a better job of promoting Separation of Concerns and isolating the View and the ViewModel from each other, while allowing easy communication between the two.

Accordingly, my ViewModel knows nothing about the View that uses it. The ViewModel is passed to the View by App. In other respects, my implementation of MVVM is pretty simple. The view model is made up of the following classes:.

MVVM and the WPF DataGrid

This composition of a view model using a main class, commands, services, and value converters is pretty typical of my MVVM implementations. I don't know if the WPF implementation can be considered Version 3. WPF data binding dramatically simplifies the process of wiring a view to its view model.

Just about everything is done as a simple binding:. The process of wiring up a view is simpler and quicker than it is in WinForms. That alone would justify a move to WPF. View model properties : My own personal style of programming is to group items and to make heavy use of regions to do the grouping. In the demo app, the view model properties are grouped into two different categories, which is pretty typical of my MVVM implementations:.

These properties hold flags and other values that the view may need to provide to the view model. I didn't need them in the demo app, so it only has the two types of properties listed above. Instead, it acts as a coordinator object, and it delegates the work to command and service objects.Blend is a user interface design tool developed by Microsoft.

The Mahapps Metro overrides the style of the default control and it gives them back to Metro UI look. What is MVVM? The MVVM pattern guides you to organize and structure the code to be more maintainable, testable, and extensible with high standards. Why MVVM? It makes your code easier to understand, maintainable and easy to test Unit test. Model It simply holds the actual data and is completely UI independent, it has nothing to do with business logic.

It simply holds the formatted data and is unaware of Model. It acts as the communication layer between Model and View. It holds the all business logics my Logics -???. Step 1 In this project we are going to follow below listed principles and you will learn implementing those principles to how to make maintainable and testable project. We are going to create our project in the below structured way. In this Project I have created Helper and Service folder for separate the Base class implementation and Data service layer.

Create a new abstract class in Helper folder, rename class name to ViewModelBase. This is base implementation logic for our Model and View Model. Change the alternating row background brush and alternation count like below image. Choose the SelectedPerson for each property then drag into each textbox like below image. Once you've dragged all the properties save all the changes. Step 8. Choose the Yes to All to conform the Changes which have done in Blend.

Output I had done some changes in visual appearance of DataGrid and textboxes you can refer to from attached project file. Hit F5 to check the Output. Get Selected Item Conclusion I hope you liked this article.

Please provide your valuable comments and suggestions. View All. Karthikeyan K Updated date Oct 19, Free Demo. Next Recommended Article. What Is Data Science?

NET Core. Factory Design Pattern With Java. NET Core 3. Private Constructor - C. Abstract Class Vs Interface - C. Using Records In C 9.IV if Model could not be updated for example when user didn't supply NotNull valuesan error is raised. I want to stay on the faulty row of the datagrid, but the high lightened row will change despite the fact that I've set SelectedIndex and SelectedValue correctly.

Thanks to almulo, I've implemented an event in the ViewModel and corresponding handler in View and it works like a charm, for anyone out there who might need help on this, these are the steps:. If the selection has just changed, you'll have to wait until you can change it programmatically once again.

This would be usually done using Dispatcher. BeginInvoke to add your call to the Dispatcher queue, so it executes after the current selection is processed. Doing this in your viewmodel is not exactly the best solution, though - MVVM-wise or in multiple UI threads scenarios. You could simply raise an event in that line passing the index inside the EventArgshave your view subscribe to that event, and fire the Dispatcher call from the event handler using this.

Dispatcher instead of Application. ToList ; if InvalidList! You can't change the selection while the selection is changing If that makes any sense :P If the selection has just changed, you'll have to wait until you can change it programmatically once again. How should the ViewModel close the form?Hi All. That value not presented in DataGrid columns. What I mean. Attachments: Up to 10 attachments including images can be used with a maximum of 3. I will show you a sample of this. The code for my MainWindow.

The picture of testing:. Try following MVVM demo:. I use hwndhost to embed a WPF - window. When the allowstransparency of the embedded window is "true", it will not be displayed under windows7 0 Answers. WPF button displaying weird blurred colors after mouse over 0 Answers.

InvalidOperationException: 'Window must be the root of the tree. Cannot add Window as a child of Visual. Skip to main content. Find posts, tags, and users I will appreciate for sample and explanation. Current Visibility: Visible to all users.

ObjectModel; using System. ComponentModel; using System. CompilerServices; using System. Windows; using System. Related Questions. When the allowstransparency of the embedded window is "true", it will not be displayed under windows7 0 Answers Rendering issues when embedding a Win32 window inside WPF 0 Answers WPF button displaying weird blurred colors after mouse over 0 Answers System.