C# WPF - ComboBox - c#

I'm working on a custom control that internally uses a ComboBox.
My problem is when the ComboBox is focused and has the drop-down open, it appears to focus the entire control. I would like to automatically highlight the first item in the drop drown, but right now you have to push the Down key to do so.
Is there a way to programmatically Highlight the first item in a ComboBox (set the readonly IsHighlighted property to true)? I believe the concept of IsHighlight within a ComboBox is different than Focus. Also, I am binding via ItemsSource, so I have no reference to ComboBoxItems.

Here's a way of doing it, although it might not cover all the cases - but you didn't provide too many details (for example, what happens when there is already an element selected? Do you still want to select the first element in the list? The code below will highlight the first element only when there is no selection in the combobox. To make it always select the first element, the DropDownOpened event should be handled too).
public MainWindow()
{
InitializeComponent();
combobox.ItemContainerGenerator.StatusChanged += new EventHandler(ItemContainerGenerator_StatusChanged);
}
void ItemContainerGenerator_StatusChanged(object sender, EventArgs e)
{
if (combobox.ItemContainerGenerator.Status == System.Windows.Controls.Primitives.GeneratorStatus.ContainersGenerated)
{
(combobox.ItemContainerGenerator.ContainerFromIndex(0) as ComboBoxItem).Focus();
}
}
(Hope I understood correctly and this is what you want to do).

It might not be what you are looking for but if you set mycombo.SelectedIndex = 0 then mycombo.IsDropDownOpen = True it should open it up and have the first item selected. It will be highlighted but will also be the value in the combobox as well. I'm not sure if this is not the desired effect though..

Related

Dropdown(list) ComboBox control field options C#

I use a ComboBox DropDown to show a number of items that can be selected. I also use a default text "Select item". It works perfectly apart from the fact that once I picked an item from the list, I can select the text and remove it (using the backspace) so that the area for the selected item is blank (see image).
I would like to prevent this or, in case this is not possible, to have the default text shown again. The latter doesn't work so far, so I tried the DropDownList but then the background of the entire list becomes grey. If I then select OwnerDrawFixed or OwnerDrawVariable in DrawMode, the background turns white again but also the font color becomes white (instead of black).
I found that I have to use DrawItem to change the layout but even that doesn't work. I simply want the same style as I indicated for DropDown. Does anyone know how to do this or where to find a similar question that has already been answered?
How about something like this?
You could also try setting the DropDownStyle to DropDownList and FlatStyle to Flat. This gives you a slightly different result.
private void InitialiseCombo(ComboBox combo)
{
combo.Items.Clear();
combo.Items.AddRange(new object[] { 3391200121, 3391200122 });
combo.DropDownStyle = ComboBoxStyle.DropDown;
combo.Text = "Select Item";
combo.KeyPress += combo_KeyPress;
}
void combo_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = true;
}
The suggested solution did not do the trick but I found a workaround to the initial problem, which is the manual deletion of the ComboBox Text, so I'll just put it here in case someone else has the same problem. When using
MyComboBox_TextChanged(object sender, EventArgs e)
I can set a restriction myself: if the text is blank, it should show the default text. If the typed text is equal to one of the item in the ComboBox, it should set the selectedItem equal to the typed text.
I also included GotFocus and Leave EventHandlers.

How to disable combox dropdown when user enters text into the combox

I have a simple combobox in c# forms which is populated from an array.
I have set AutoCompleteMode to SuggestAppend and AutoCompleteSource to ListItems. This allows me to filter through the list quickly by typing a string into the combobox and matching items are displayed as I type along. This works great.
However, when the drop down list is open and I start typing, the filtered list appears on top of the dropdown list but I cannot select from the filtered list but only from the drop down.
How to disable drop down list while open as soon as user enters a character into the combobox.
Currently only have one method for the combobox
private void SelectJobDropdown_SelectedIndexChanged(object sender, EventArgs e)
{
//plenty of code here
}
I have tried adding other methods for the combobox such as KeyPress or Keydown but none seems to be working for as I'm very likely doing something wrong
Using Visual Studio 2015
If I understood you correctly you don't like the overlapping list over the old drop down. Since you type letters into the ComboBox I would suggest to use the comboBox1_TextUpdate event. This nice line of code should fix your problem:
private void comboBox1_TextUpdate(object sender, EventArgs e)
{
comboBox1.DropDownStyle = ComboBoxStyle.Simple;
Setting the ComboBox.DropDownStyle property, which
specifies whether the list is always displayed or whether the list is displayed in a drop-down[...]
to ComboBoxStyle.Simple, which
Specifies that the list is always visible and that the text portion is editable. This means that the user can enter a new value and is not limited to selecting an existing value in the list.
will remove the original dropdown (long list) and only the filtered results remain.

How can you re-focus the first selected row in the WPF DataGrid when it gains focus?

Simple question with an as-of-yet unfound answer. We have a WPF DataGrid on our window which supports multi-select. Say it has ten items in it and you have items six through ten selected. If you tab away from the control, when the control gets focus again, the first item is focused but not selected. The selection still remains on items six through ten. This is made worse for us because we hide the focus rectangle, instead relying on the selection highlight, which is what the user would expect to happen.
I've tried responding to the IsKeyboardFocusWithinChanged event as shown here, including with and without the dispatcher, figuring maybe something else was changing it after the fact, but still no avail.
private void TestDataGrid_IsKeyboardFocusWithinChanged(object sender, DependencyPropertyChangedEventArgs e)
{
if(!(bool)e.NewValue)
return;
Dispatcher.Invoke(new Action(() =>
{
var firstSelectedItem = VariableValuesDataGrid.SelectedItem;
if(firstSelectedItem != null)
VariableValuesDataGrid.CurrentItem = firstSelectedItem;
}), DispatcherPriority.Background);
}
Any idea how to get around this?
I'm not really that familiar with the WPF DataGrid but I suspect you must be dealing with the same issues of the old forms DataGridView.
Setting the selected row only highlights and doesn't actually focus it. And the CurrentRow property is unfortunately private but the CurrentCell property is not and can be used to set the selection instead.
myDataGrid.CurrentCell = myDataGrid.Rows[i].Cells[0];
myDataGrid.Rows[i].Selected = True;

How to select a ListBoxItem which is already selected OR to highlight previous selected ListBoxItem after setting SelectedIndex to -1?

I'm programming a simple listbox in windows phone 7. The listbox has some items and when I click any of items the app navigates to a new page.
From beginning to here, everything is good.
But I want end-user can select the item again which causes navigate to the next page again. But listbox as it is, doesn't allow me to select an already selected item again.
I tried to do this for allowing to select an item again.
private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if(ListBox.SelectedIndex != -1 )
{
NavigationService.Navigate(uri);
ListBox.SelectedIndex = -1;
}
}
I have alreadhy edited the ListBoxItemTemplate to highlight selected item, but when I use above code, I cannot highlight the selected item, because it changes SelectedIndex too fast.
So how can I allow user to select a selected item or how can I highlight previous selected item. Any suggestions or tips?
EDIT:
When using a normal ListBox , I can simply use :
listboxitem1.Background = new SolidColorBrush(Color.Blue);`
But when I edit template of listbox item this does throw exception, so I cannot still do this.
Look into implementing one of the other Event handlers for Mouse events on the ListBox. Such as the Click Event. You can detect when the user clicks the ListBox without changing the selected index by keeping track of the previous selected index value.
Well, you can edit the template of ListBoxItem and add a grid, fully front of listbox item. And bind the visibility property of this grid.
After this, you can change of the visibility according to selected index. This approach should work well if you're using a navigation with listbox.
Hope it works!

A ComboBox Data Binding Question

I have an interesting data binding question related to combobox. Hope someone has some good suggestion.
I have a simple form, it contains a file picker and a comboxbox. Every time a file is picked, I read a list of strings from the file to a List object and I set comboBox.DataSource = listOfStrings.
In the form load event, I set comboBox.DataBindings.Add("SelectedItem", myObject, "PickedValue");
The purpose is clear: every time a string is selected from the combobox, I want to write the string to myObject.PickedValue.
That is the whole story.
Now I launch the form, rather than go pick a file, I check the combobox first. Of course, at this point, comboBox.DataSource is null, comboBox.SelectedItem is null, too. But the data binding on the comboBox is already setup (since the setting is in form load event). Now my focus cannot be moved from the combobox to anywhere else.
I think the reason is, when I try to check the combobox, it has null as SelectedItem. When I try to move the focus to somewhere else, the data binding of the combobox is triggered. Underlying, it tries to convert the selected item to string and update myObject.PickedValue with that converted string. Since you cannot convert a null to a string, the data binding validation fails, and the validation mechanism doesn't allow my focus to be moved elsewhere and I am sucked at this moment, cannot even move to pick a file.
My question is, what is the normal binding setup work-flow for my application scenario to prevent this trap? What is the correct order of setting up such a data binding so I can check my combobox before its data source is filled by something?
FYI, I tried to bind myObject.PickedValue to SelectedText property of the combobox (I noticed that SelectedText is a string and never be null, even when SelectedItem is null). But interestingly, even if I select something from the combobox, SelectedText is still empty string when data binding is triggered. What's wrong here?
Thanks for any help.
The failure is a little simpler than you describe: Your ComboBox will fail just because there is no selected item, because there's nothing to select from.
I would just disable the ComboBox if there's nothing to select from. It's pretty easy to do. Remember to hook up a PropertyChanged event in your data object; the binding source will find it automatically with reflection.
class MyData
{
public event PropertyChangedEventHandler PropertyChanged;
// ...
public HasListOfStrings { get { return ListOfStrings != null && 0 < ListOfStrings.Count; } }
private void LoadListOfStrings
{
// ... load the list of strings ...
if ( PropertyChanged) {
PropertyChanged(this, "ListOfStrings");
PropertyChanged(this, "HasListOfStrings");
}
}
}
In the designer, bind the 'Enabled' property of the 'ComboBox' to the HasListOfStrings property. You can do it in code with:
listOfStringsComboBox.Bindings.Add ("Enabled", bindingSource, "HasListOfStrings");
I also recommend you change the AutoValidate property of the container (or container's container) to EnableAllowFocusChange.
This doesn't seem right; it should be possible to set a string property to null. Possibly the focus problem lies elsewhere. Have you tried setting a breakpoint on your property setter to confirm your theory?
The SelectedText property of a combo box refers to text that has been selected in the text portion of the combobox. This only works if the dropdown style is set to combo. Basically it's the selected text of the text box portion of the combo control (the reason a combobox is called "combo" is because it is a combination of a textbox and a selection list). You would ordinarily expect this property to be empty unless the user was editing the text portion of the combo.
If you want a workaround for this problem that is consistent with a good user experience, try disabling the combo box on form load, then enabling it when a file is picked.

Categories