Quantcast
Channel: Windows Presentation Foundation (WPF) forum
Viewing all articles
Browse latest Browse all 18858

DataGrid Focus from code?

$
0
0

Hi,

I have DataGrid as follows;

<DataGrid   
    Name="dg_results"
    CanUserAddRows="False" 
    CanUserDeleteRows="False" 
    CanUserResizeColumns="True" 
    CanUserSortColumns="True"
    CanUserReorderColumns="True" 
    SelectionUnit="FullRow"
    SelectionMode="Single">

When the user clicks a button, I set the DataGrid's ItemSource (an ObservableCollection). This works fine. If the user clicks on the DG once, it gets focus (of some kind) and the row is selected. Up/Down arrow then work as expected, ie they change the selected Row.

What I'm trying to do, and failing, is setting this focus in codebehind. Essentially I want to remove the step where the user clicks on the DG with their mouse.

The following code partially works;

//dg_results.Focus(); // I tried this too
object item = dg_results.Items[0];
dg_results.SelectedItem = item;
Keyboard.Focus(dg_results);

This selects the Row and gives it focus, but the focus/behaviour is slightly different to when clicking on the DG.

The problem is what happens next, after the down/up arrow is pressed. The Row and DG seem to lose focus. Not too sure what is happening. 

My question is this;

How can I, using codebehind, do all of the following;

1. Give a DataGrid focus

2. Select the first Row

3. (in such a way that) pressing Up/Down arrow will select another Row

Many thanks



Viewing all articles
Browse latest Browse all 18858

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>