The problem of choosing WPat Datagrid

In my WPF application, I have one datagrid and one text field. In the textChanged event of a text field, 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 line does not change to blue , which makes it difficult to view the selection.

I really need this because in the PreviewKeyDown event of the text field, 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 text field is focused and the user presses the Up or Down key, the selection does not change.

Any idea how I can make the selected item in a datagrid change its color to blue?

Another thing: it works on my virtual machine !! With the same code! How is this possible?

I think this is aeroglass, but I am changing the theme to Windows 7 Basic (the same thing in a virtual machine) and still do not work.

Thank you and sorry for my english.

+4
source share
1 answer

Could you try using SelectedItem? you can always create a new property and bind to it, and then set this element directly, rather than use the selected index. Hope this triggers 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 do not forget to set the binding!

 SelectedItem="{Binding SelectedItem}" 

hope this helps!

+1
source

Source: https://habr.com/ru/post/1441810/


All Articles