Following code of my WPF
app is showing the default value as blank instead of CA
. I've tested in debug mode that the cmbStates.SelectedValue
is showing NULL
after I move to the next line while using F11
in VS2017
. I've tried moving the code to Windows loaded event but still the exact same behavior.
Note:
- According to this post it should work, but it's not. Maybe, my case is a bit different
- The code successfully displays the
comboBox
values but the top of the comboBox is blank unless I manually select a particular value for the comboBox.
Question: What I may be missing here and how can we make it work?
XAML:
<Window x:Class="WpfTestApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
....
....
>
<Grid>
....
....
<ComboBox x:Name="cmbStates" IsEditable="True" SelectedValuePath="Content" SelectionChanged="cmbStates_SelectionChanged" />
....
....
</Grid>
</Window>
Code Behind for MainWindow:
....
public MainWindow()
{
InitializeComponent();
cmbStates.ItemsSource = new List<string>() {"OH", "VA", "CA", "TN", "CA", "DE"};
cmbStates.SelectedValue = "CA";
}
....
UPDATE:
Please note that the question is more specific to setting the default value in Code Behind
and not in XAML
because the list is quite longer than shown in this post (for brevity), and that the default value is not always "CA" - it varies based on the business requirements. You can think of "CA" as some string variable value instead, but the idea is the same.