It seems nobody has yet found a way to set the comboboxitem as selected with a SelectedItem="Binding Property".
Is the solution to use a IsSelected Property in the ViewModel object within the combobox itemssource?
When you set the SelectedItem property to an object, the ComboBox attempts to make that object the currently selected one in the list. If the object is found in the list, it is displayed in the edit portion of the ComboBox and the SelectedIndex property is set to the corresponding index.
Using an enum to fill a combo box allows for easy use of the SelectedItem method to programmatically select items in the combobox as well as loading and reading from the combobox. Show activity on this post.
Practical Data Science using Python It can be set by listing all the records in a variable that needs to be present in the Combobox. By specifying the index of the particular value in the current(index) method, we can set the default value in the Combobox widget.
Not sure why you can't data bind to SelectedItem on a ComboBox without seeing your code. Below shows you how to do it using a CollectionView which has current item management built in which comboboxes supports. CollectionView has a CurrentItem get property you can use to get currently selected.
XAML:
<Window x:Class="CBTest.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<StackPanel>
<ComboBox
ItemsSource="{Binding Path=Names}"
IsSynchronizedWithCurrentItem="True">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}" />
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
<TextBlock Text="{Binding Path=Names.CurrentItem}" />
</StackPanel>
</Window>
Code behind:
using System.Collections.Generic;
using System.Windows;
using System.Windows.Data;
namespace CBTest
{
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
DataContext = new VM();
}
}
public class VM
{
public VM()
{
_namesModel.Add("Bob");
_namesModel.Add("Joe");
_namesModel.Add("Sally");
_namesModel.Add("Lucy");
Names = new CollectionView(_namesModel);
// Set currently selected item to Sally.
Names.MoveCurrentTo("Sally");
}
public CollectionView Names { get; private set; }
private List<string> _namesModel = new List<string>();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With