Reputation: 241
I have an ObservableCollection<string>
named MyCollection
containing "A", "B", "C", "D"
. I create a view like this:
<ComboBox x:Name="MyComboBox"
ItemsSource="{Binding MyCollection}"
SelectedIndex="{Binding 3}"/>
<Button Click="OnClickButton">Button</Button>
Then my codebehind looks like this:
public partial class MyClass {
private string _mySelection;
public string MySelection
{
get { return _mySelection; }
set
{
_mySelection = value;
}
}
public void OnClickButton(object sender, RoutedEventArgs e) {
MySelection = (MyComboBox.SelectedItem).ToString();
MessageBox.Show(MySelection);
}
This is fine. The ComboBox populates just as it should, and MySelection
is set properly and appears in the message box. But currently, my ComboBox appears blank in the user interface until the user clicks on it and selects an option. I want option C to be the default value, and if the user doesn't select anything, then MySelection
will be set to C
.
But no matter how many different combinations of SelectedItem
, SelectedValue
, and SelectedIndex
I try, I can't get it to work. The ComboBox always starts off empty.
How can I do this?
Upvotes: 0
Views: 66
Reputation: 189
Set a default value of the _mySelection
field, i.e. "C"
Or, more general, set the value of MySelection
to the desired default value after construction.
Also make sure that the MySelection
property fires a change notification.
public class MyViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public ObservableCollection<string> MyCollection { get; }
= new ObservableCollection<string>();
private string mySelection;
public string MySelection
{
get { return mySelection; }
set
{
mySelection = value;
PropertyChanged?.Invoke(this,
new PropertyChangedEventArgs(nameof(MySelection)));
}
}
}
Initialize the DataContext of the view with an instance of MyViewModel
:
public MainWindow()
{
InitializeComponent();
var vm = new MyViewModel();
vm.MyCollection.Add("A");
vm.MyCollection.Add("B");
vm.MyCollection.Add("C");
vm.MyCollection.Add("D");
vm.MySelection = "C";
DataContext = vm;
}
private void OnClickButton(object sender, RoutedEventArgs e)
{
MessageBox.Show(((MyViewModel)DataContext).MySelection);
}
Upvotes: 1