I got a sample mvvm app. The UI has a textbox, a button and a combobox. when I enter something in the textbox and hit the button, the text I enter gets added to an observablecollection. The Combobox is bound to that collection. How do I get the combobox to display the newly added string automaticly?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
- How to know full paths to DLL's from .csproj f
If the ComboBox is bound to an ObservableCollection, the ComboBox will be updated as soon as the collection is changed.
That's the advantage of using an ObservableCollection - you don't need to do any extra coding to update the UI.
If this is not the behavior you're seeing, perhaps you can post some code/xaml.
As I understand correctly, you want to add an item and select it. Here is the example how it can be done using ViewModel and bindings.
Xaml:
ViewModel:
The
MainViewModel
has 3 properties (one for theTextBox
and two other for theComboBox
) and the methodAddNewItem
without parameters.The method can be triggered from a command, but there is no standard class for commands, so I will call it from the code-behind:
So you must explicitly set an added item as selected after you add it to a collection.
Because the method
OnItemsChanged
of theComboBox
class is protected and can't be used.