Reset comboxbox selection after a selection is made - wpf

I have a combobox that is created with data from a dataset
foreach(var item in ds.MiDESValues)
{
string comboboxtext = ds.MiDESValues.Rows[k][1].ToString();
sFactorCB.Items.Add(comboboxtext);
k++;
}
On a selectionchanged event it will populate a listbox with that selection
private void sFactors_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
string add = sFactorCB.SelectedValue.ToString();
var svalue = ds.MiDESValues.Rows[0][2].ToString();
int Svalue = int.Parse(svalue);
SValue.Add(svalue);
SelectionListBox.Items.Add(add);
SelectionBox.Add(add);
// when a new item is added to Selection list box, select it and show it
// this will keep the last item highlighted and as the list grows beyond
// the view of the list box, the last item will always be shown
SelectionListBox.SelectedIndex = SelectionListBox.Items.Count - 1;
SelectionListBox.ScrollIntoView(SelectionListBox.SelectedItem);
}
That list box then used to populate a listbox used on the next page. If I navigate to the next page and then navigate back, the combobox is still showing the last selection I made therefor the listbox is being populated with that value.
I have tried setting the selectedindex of the combobox to sFactorCB.SelectedIndex = -1;, at the end of the sFactors_SelectionChanged event but i get System.NullReferenceException. How can I get the combobox to reset back to a non-selected item state? Thanks

Actually, you are doing it correctly. To clear the selection either set the SelectedIndex to -1 or the SelectedItem to null.
The problem is that once you do that your sFactors_SelectionChanged gets called again and since there is no current selection, the SelectedValue property is null thus causing the following to fail:
string add = sFactorCB.SelectedValue.ToString();
How to solve this sort of depends on your intended results when nothing is selected. The simplest thing to do would be to just check for nothing selected at the start of the handler and simply return.
private void sFactors_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (sFactorCB.SelectedIndex == -1 || sFactorCB.SelectedValue == null)
return;
string add = sFactorCB.SelectedValue.ToString();
...

Related

How to retain Focus of the first row after sorting and searching in the datagrid?

When my datagrid loads up I am able to get the focus of the first row by providing selected index=0 in the xaml but when I perform searching the focus gets lost so I want focus to be retain at the first row no matter I do sorting and searching on the datagrid.
Here is my code that searches particular thing in the datagrid.
private void TextBox_TextChanged(object sender, RoutedEventArgs e)
{
TextBox STB = (TextBox)sender;
this.SearchValue = STB.Text;
//ContentPresenter CP = (ContentPresenter)STB.TemplatedParent;
//DataGridColumnHeader DGCH = (DataGridColumnHeader)CP.TemplatedParent;
//DataGridColumn DGC = DGCH.Column;
//this.ColumnName = DGC.Header.ToString();
this.Datalist.Filter = this.CustomeFilter;
DataGrid dataGrid = this as DataGrid;
dataGrid.CurrentCell = new DataGridCellInfo(
dataGrid.Items[0], dataGrid.Columns[0]);
dataGrid.BeginEdit();
}
In above code I am trying to get the focus of the current cell but all in vain.
private bool CustomeFilter(object item)
{
SymbolData ltpObj = item as SymbolData;
//WpfApplication1.Model.LtpMessage ltpObj = item as WpfApplication1.Model.LtpMessage;
string values = (string)ltpObj.Symbol.ToString();
values = values.ToUpper();
//return values.StartsWith(this.SearchValue.ToString().ToUpper());
if (values.StartsWith(this.SearchValue.ToString().ToUpper()))
{ return true; }
else
return false;
}
You should read this:
How to programmatically select and focus a row or cell in a DataGrid in WPF: https://blog.magnusmontin.net/2013/11/08/how-to-programmatically-select-and-focus-a-row-or-cell-in-a-datagrid-in-wpf/
You can select and focus a row or cell of a DataGrid programmatically 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 DataGridCell object as described in the blog post above. There are code samples included.
You cannot simply set the SelectedItem or SelectedIndex property of the DataGrid to focus the row or cell though.

Windows Forms: Manually paint SelectedItem of ComboBox

I have a ComboBox (ToolStripCombobox, to be more precise) filled with items of type KeyValuePair<Int32, FontFamily>. I managed to have the Items beeing painted manually by using the DrawItem event. So every Item is painted with the FontFamily of the corresponding KeyValuePair. This works fine for the DropDownList, but when I select an Item out of the List and the list closes, the text in the ComboBox says something like "[21, [FontFamily: Name=Arial]]" which is most likely the result of SelectedItem.ToString().
Any ideas how to solve this problem?
here is the code of my custom DrawItem method:
private void fontComboBoxDrawItem(object sender, DrawItemEventArgs e)
{
e.DrawBackground();
if ((e.State & DrawItemState.Focus) != 0)
{
e.DrawFocusRectangle();
}
Brush objBrush = null;
var itemToDraw = this.fontComboBox.Items[e.Index];
KeyValuePair<Int32, FontFamily> windowsFontItem = (KeyValuePair<Int32, FontFamily>)itemToDraw;
objBrush = new SolidBrush(e.ForeColor);
e.Graphics.DrawString(windowsFontItem.Value.Name, new Font(windowsFontItem.Value, e.Font.Size), objBrush, e.Bounds);
if (objBrush != null)
{
objBrush.Dispose();
}
objBrush = null;
}
Update:
It works as expected, when I set the DropDownStyle of the ComboBox to ComboBoxStyle.DropDownList
But I´d rather use ComboBoxStyle.DropDown, so you can edit the Text to search for Fonts.

WPF Datagrid drag and drop questions

I have a WPF Datagrid and I'm implementing drag and drop functionality.
The datagrid has a list of "files" and the user can drag them and copy the file to the desktop.
This is done like this:
string[] files = new String[myDataGrid.SelectedItems.Count];
int ix = 0;
foreach (object nextSel in myDataGrid.SelectedItems)
{
files[ix] = ((Song)nextSel).FileLocation;
++ix;
}
string dataFormat = DataFormats.FileDrop;
DataObject dataObject = new DataObject(dataFormat, files);
DragDrop.DoDragDrop(this.myDataGrid, dataObject, DragDropEffects.Copy);
I have two questions:
1. When I want to drag multiple items- this is a problem because after I select a couple and start clicking on one to start dragging- only that gets selected and the other items get deselected. I tried the solution that is given here but for some reason it doesn't work.
2. I want to remove the dragged item from the datagrid after it is copied. The problem is that I don't know how to check if the file was copied or whether the user just dragged it on the screen without copying it.
I hope you can help me solve these problems.
Thanks!
I think this i what you are looking for:
add this code to the DataGrid__PreviewMouseLeftButtonDown event handler:
private void DataGrid_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
this.startingPosition = e.GetPosition(null);
DependencyObject dep = (DependencyObject)e.OriginalSource;
// iteratively traverse the visual tree until get a row or null
while ((dep != null) && !(dep is DataGridRow))
{
dep = VisualTreeHelper.GetParent(dep);
}
//if this is a row (item)
if (dep is DataGridRow)
{
//if the pointed item is already selected do not reselect it, so the previous multi-selection will remain
if (songListDB.SelectedItems.Contains((dep as DataGridRow).Item))
{
// now the drag will drag all selected files
e.Handled = true;
}
}
}
and now the draging won't change you selection.
Have a good luck!
I used that article to write my answer
Improved on finding the row.
Also selecting the clicked row when not dragging is added.
This now behaves exactly as other Microsoft selectors (eg Outlook)
public TreeDataGrid()
{
Loaded += TreeDataGrid_Loaded;
LoadingRow += new EventHandler<DataGridRowEventArgs>(TreeDataGrid_LoadingRow);
}
#region MultiSelect Drag
object toSelectItemOnMouseLeftButtonUp;
void TreeDataGrid_LoadingRow(object sender, DataGridRowEventArgs e)
{
e.Row.PreviewMouseLeftButtonDown += new MouseButtonEventHandler(Row_PreviewMouseLeftButtonDown);
e.Row.PreviewMouseLeftButtonUp += new MouseButtonEventHandler(Row_PreviewMouseLeftButtonUp);
}
void Row_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
DataGridRow row = (DataGridRow)sender;
toSelectItemOnMouseLeftButtonUp = null; // always clear selecteditem
if (SelectedItems.Contains(row.Item)) //if the pointed item is already selected do not reselect it, so the previous multi-selection will remain
{
e.Handled = true; // this prevents the multiselection from disappearing, BUT datagridcell still gets the event and sets DataGrid's private member _selectionAnchor
toSelectItemOnMouseLeftButtonUp = row.Item; // store our item to select on MouseLeftButtonUp
}
}
void Row_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
DataGridRow row = (DataGridRow)sender;
if (row.Item == toSelectItemOnMouseLeftButtonUp) // check if it's set and concerning the same row
{
if (SelectedItem == toSelectItemOnMouseLeftButtonUp) SelectedItem = null; // if the item is already selected whe need to trigger a change
SelectedItem = toSelectItemOnMouseLeftButtonUp; // this will clear the multi selection, and only select the item we pressed down on
typeof(DataGrid).GetField("_selectionAnchor", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(this, new DataGridCellInfo(row.Item, ColumnFromDisplayIndex(0))); // we need to set this anchor for when we select by pressing shift key
toSelectItemOnMouseLeftButtonUp = null; // handled
}
}
#endregion

GridView loses SelectedIndex value when ItemsSource is refreshed

Microsoft I think this may be a bug. Have a ListView GridView to display a single record.
Naturally the down arrow key navigates through the ListViewItems. That is the behavior I expect. In XAML the ItemsSource and SelectedIndex is bound. The behavior I want is the right and left arrow keys to navigate to the next and prior record.
The way I achieved this is to handle ListView PreviewKeyDown Event. The problem I had is the SelectedIndex is reset to -1 when the ItemSource is refreshed and I want it to stay on the old SelectedIndex. So I had to manually reset the SelectedIndex as shown below.
Here is my problem: After AND ONLY DIRECTLY AFTER a left arrow or right arrow key the up and down keys do not pass the correct value for SelectedIndex.
For example SelectedIndex = 4 then right arrow and then down key the value passed to SelectedIndex is 0 and the value passed should be 4. The ListView is visually on SelectedIndex 4 so it is like it knows the SelectedIndex is 4 but it also does not know. If I do not change the ItemsSource the up and down arrow keys work correctly. I tried KeyDown and KeyUp events but in the case those events just don't fire at all in the fail condition described above.
WPF 4.0 Visual Studio 2010.
private void lvCurDocFields_PreviewKeyDown(object sender, KeyEventArgs e)
{
Debug.WriteLine("lvCurDocFields_PreviewKeyDown " + e.Key.ToString());
e.Handled = false;
Int32 lastIndex;
switch (e.Key) // e.KeyCode
{
case Key.Right:
lastIndex = lvCurDocFields.SelectedIndex;
App.StaticGabeLib.Search.SelectedDocIndex++;
if (lvCurDocFields.SelectedIndex != lastIndex)
{
lvCurDocFields.SelectedIndex = lastIndex;
}
e.Handled = true;
break;
case Key.Left:
lastIndex = lvCurDocFields.SelectedIndex;
App.StaticGabeLib.Search.SelectedDocIndex--;
if (lvCurDocFields.SelectedIndex != lastIndex)
{
lvCurDocFields.SelectedIndex = lastIndex;
}
e.Handled = true;
break;
}
base.OnPreviewKeyDown(e);
}
Normally, I store a reference to the item that was selected, update the list, and re-select it afterwards. ListIndex isn't a reliable way to maintain a selection if things are inserted or deleted from the list.
if(MyListControl.Items.Contains(PreviouslySelectedItem)) MyListControl.SelectedItem = PreviouslySelectedItem;

Is ScrollIntoView synchronized in virtualstackpannel (Especially in WPF DataGrid)?

We have a problem for focus a cell of DataGrid after Its data of bounded collection has Refreshed.
for example we set a filter for its collection and then we want to refocus a stored cell of stored column.
Is it true that we think a call to ScrollIntoView is synchronized it means after call it our desired row and cell are created and we can set focus? (again it means after we call to ScrollIntoView , Is it true we think that Itemsgenerator finished its work and we can surly find our desired cell)
$
//set filter of DataGrid Collection
DataGrid_Standard.ScrollIntoView(rowNumber,cellNumber);
//we sure our desired cell are created now
DataGridRow row = (DataGridRow)DataGrid_Standard.ItemContainerGenerator.ContainerFromIndex(index);
if (row == null)
{
// may be virtualized, bring into view and try again
DataGrid_Standard.ScrollIntoView(DataGrid_Standard.Items[index]);
row = (DataGridRow)DataGrid_Standard.ItemContainerGenerator.ContainerFromIndex(index);
}
DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(rowContainer);
// try to get the cell but it may possibly be virtualized
DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
// now try to bring into view and retreive the cell
DataGrid_Standard.ScrollIntoView(rowContainer, DataGrid_Standard.Columns[column]);
cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column); cell.focus();
Related
Here's a datagrid Selection changed event handler that moves a virtualized row into view and then sets the focus to that row. This works for me:
private void DataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
DataGrid dg = (DataGrid)sender;
if (dg.SelectedItem == null) return;
dg.ScrollIntoView(dg.SelectedItem);
DataGridRow dg_row = (DataGridRow)dg.ItemContainerGenerator.ContainerFromItem(dg.SelectedItem);
if (dg_row == null) return;
dg_row.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
}
EDIT: Using the dg_row.MoveFocus method had an undesriable effect (a checkbox column required two clicks to set instead of one) and it worked better for me to just use
dg_row.Focus();
Action action = () =>
{
dg .ScrollIntoView(dg .SelectedItem);
var item = dg.ItemContainerGenerator.ContainerFromIndex(index) as DataGridRow;
if (item == null) return;
item.Focus();
};
Dispatcher.BeginInvoke(DispatcherPriority.Background, action);
This should work fine for your case.

Resources