4
votes

In my WPF application I have one datagrid and one textbox. In the textChanged event of the textbox, I put this:

myDatagrid.ItemsSource = 
myListOfObjects.Where(item => item.Name.Contains(MyTextBox.Text)); //Filter

if (myDatagrid.Items.Count > 0)  // If no itens, then do nothing
{
     myDatagrid.SelectedIndex = 0;  // If has at least one item, select the first
}

myDatagrid.Items.Refresh();

Note that I force the selection when the text changes, in the first row of the DataGrid.

But unfortunately, the color of the row does not change to blue, making it hard to see the selection.

I realy need this, because in the PreviewKeyDown event of the textbox I have this:

    private void myTextBox_PreviewKeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Up)
        {
            if (!(myDataGrid.SelectedIndex <= 0))
            {
                myDataGrid.SelectedIndex--;  // Go one position Up
            }
        }

        if (e.Key == Key.Down)
        {
            if (!(myDataGrid.SelectedIndex == myDataGrid.Items.Count - 1))
            {
                myDataGrid.SelectedIndex++;  // Go one position Down
            }
        }
    }

So, when the textbox is focused and the user press the Up or the Down key, the selection does not appear to change.

Any idea of how I can make the selected item on the datagrid change it's color to blue?

Other thing: in my virtual machine, it works!! With the same code! How it's possible?

I think that is the aeroglass, but I change the theme to the Windows 7 Basic (same in the virtual machine) and still don't work.

Thanks, and sorry for my english.

1

1 Answers

1
votes

Could you try using SelectedItem? you could always create a new property and bind to this and then set this item directly rather than using the selected index. Hopefully this would trigger any additional logic in the DataGrid control :)

//Declare property outside of method
public ObjectType SelectedItem { get; set; }

//Set datacontext on load
DataContext = this;

myDatagrid.ItemsSource = myListOfObjects.Where(item => item.Name.Contains(MyTextBox.Text)); //Filter

if (myDatagrid.Items.Count > 0)  // If no itens, then do nothing
{
     SelectedItem = myDatagrid.ItemSource[0];  // If has at least one item, select the first
}

myDatagrid.Items.Refresh();

Also don't forget to set your binding!

SelectedItem="{Binding SelectedItem}"

hope that helps!