This is the WPF-Datagrid I use:
<DataGrid Grid.Row="1" x:Name="products" CanUserAddRows="true" MouseDoubleClick="products_MouseDoubleClick" InitializingNewItem="products_InitializingNewItem" IsReadOnly="True"/>
The products-Dataset has a Property called "Nickname" and is sorted by this property. When the user presses a letter (for example "m") I want my datagrid to select the next Row with a nickname starting with "m".
In short: I want my dataGrid show the standard behavior like most datagrids in Windows (e.g. explorer).
This code:
private void products_KeyUp(object sender, KeyEventArgs e)
{
foreach (ProductDatasource item in products.Items)
{
if (item.Nickname.StartsWith(e.Key.ToString()))
{
Debug.Print("Found it, but how to set the selection?");
}
}
}
will find the first Item which starts with the letter. But how can I select this item?
And as pretty every Grid in windows shows the same behavior (even in a more complicated way like starting the search from the current position; if you press 2 keys shortly after another like "mi" it searches for the next item starting with "mi") I wonder if the DataGrid has built in behavior I can use to do this?
CodePudding user response:
Set the SelectedItem
property of the DataGrid
:
private void products_KeyUp(object sender, KeyEventArgs e)
{
foreach (ProductDatasource item in products.Items)
{
if (item.Nickname.StartsWith(e.Key.ToString()))
{
products.SelectedItem = item;
}
}
}