1

New/learning WPF with MVVM. I'm trying to get a ComboBox to display a default value when linking with a Label:

<StackPanel ...>
    <ComboBox Name="cboMonth"
        ItemsSource="{Binding MonthsList, Mode=OneWay}"
        DisplayMemberPath="month"
        SelectedIndex="{Binding DisplayCurrentIntMonth,  Mode=Default}"
        SelectedItem="{Binding SelectedMonth, Mode=Default}" />
    <Label Content="{Binding SelectedMonth.month}" />
</StackPanel>

MonthList is of type Month (populated with 01-January, 02-February, ...etc); Month has single property, string month.

DisplayCurrentIntMonth returns an int:

public int DisplayCurrentIntMonth
{    
    get
    {                
        DateTime today = DateTime.Today;
        return selectedIntMonth = today.Month - 1;
    }
    set
    {                
        if (selectedIntMonth != value)
        {           
            RaisePropertyChanged("DisplayCurrentIntMonth");
        }
    }
}

SelectedMonth returns a Month:

public Month SelectedMonth
{
    get
    {                
        return selectedMonth;
    }
    set
    {                
        if (selectedMonth != value)
        {
            selectedMonth = value;
            RaisePropertyChanged("SelectedMonth");
        }
    }
}

The code above will NOT display a default value (in the ComboBox) with

SelectedIndex="{Binding DisplayCurrentIntMonth, Mode=Default}"

but will display a default value (and function completely as desired) with no binding:

SelectedIndex="5"

I've looked at this link (among many others) but no luck. Have spent several hours Googling...

Why is the ComboBox default value (should be 06-June) not populating when the app first renders?

With help from Pedro, got the ComboBox to sync with a Label and ComboBox shows desired item:

<StackPanel ...>
    <ComboBox Name="cboMonth"
        ItemsSource="{Binding MonthsList, Mode=TwoWay}"
        DisplayMemberPath="month"
        SelectedIndex="{Binding DisplayCurrentIntMonth,  Mode=TwoWay}"
        SelectedItem="{Binding SelectedMonth, Mode=Default}" />
    <Label Content="{Binding SelectedItem.month, ElementName=cboMonth}"/>
</StackPanel>
Community
  • 1
  • 1
Mark S
  • 103
  • 2
  • 8
  • Don't set SelectedItem and SelectedIndex at the same time. – Clemens Jun 29 '15 at 20:08
  • Thanks. Yes, my updated code (http://stackoverflow.com/questions/31124331/wpf-mvvm-selectedindex-binding-property-not-updating-when-combobox-selection-ch) reflects this. – Mark S Jun 29 '15 at 21:41

0 Answers0