I have a problem with the SelectedItem in my ComboBox.
<ComboBox Name="cbxSalesPeriods"
ItemsSource="{Binding SalesPeriods}"
DisplayMemberPath="displayPeriod"
SelectedItem="{Binding SelectedSalesPeriod}"
SelectedValuePath="displayPeriod"
IsSynchronizedWithCurrentItem="True"/>
If I open the ComboBox, I see the values.
If I select an item, the selected Item won't be shown.
Has anybody an idea?
In my ViewModel I have these two properties:
public ObservableCollection<SalesPeriodVM> SalesPeriods { get; private set; }
private SalesPeriodVM selectedSalesPeriod;
public SalesPeriodVM SelectedSalesPeriod
{
get { return selectedSalesPeriod; }
set
{
if (selectedSalesPeriod != value)
{
selectedSalesPeriod = value;
RaisePropertyChanged("SelectedSalesPeriod");
}
}
}
These are a few properties from the class :
public SalesPeriodVO Vo
{
get { return period; }
}
public int Year
{
get { return period.Year; }
set
{
if (period.Year != value)
{
period.Year = value;
RaisePropertyChanged("Year");
}
}
}
public int Month
{
get { return period.Month; }
set
{
if (period.Month != value)
{
period.Month = value;
RaisePropertyChanged("Month");
}
}
}
public string displayPeriod {
get
{
return this.ToString();
}
}
public override string ToString()
{
return String.Format("{0:D2}.{1}", Month, Year);
}
EDIT: The Following happens If I remove the Property DisplayMemberPath:
You seem to be unnecessarily setting properties on your
ComboBox
. You can remove theDisplayMemberPath
andSelectedValuePath
properties which have different uses. It might be an idea for you to take a look at the Difference between SelectedItem, SelectedValue and SelectedValuePath post here for an explanation of these properties. Try this:Furthermore, it is pointless using your
displayPeriod
property, as the WPF Framework would call theToString
method automatically for objects that it needs to display that don't have aDataTemplate
set up for them explicitly.UPDATE >>>
As I can't see all of your code, I cannot tell you what you are doing wrong. Instead, all I can do is to provide you with a complete working example of how to achieve what you want. I've removed the pointless
displayPeriod
property and also yourSalesPeriodVO
property from your class as I know nothing about it... maybe that is the cause of your problem??. Try this:Then I added two properties into the view model:
Then initialised the collection with your values:
And then data bound only these two properties to a
ComboBox
:That's it... that's all you need for a perfectly working example. You should see that the display of the items comes from the
ToString
method without yourdisplayPeriod
property. Hopefully, you can work out your mistakes from this code example.