I have the following WPF Combobox:
<Window.Resources>
<CollectionViewSource x:Key="performanceItemsource" Source="{Binding Path=SelectedReport.Performances}" >
<CollectionViewSource.SortDescriptions>
<scm:SortDescription PropertyName="Name"/>
</CollectionViewSource.SortDescriptions>
</CollectionViewSource>
</Window.Resources>
...
<ComboBox Name="cbxPlanPerf" Grid.ColumnSpan="2"
SelectedValuePath="MSDPortfolioID" DisplayMemberPath="Name"
SelectedValue="{Binding Path=PlanPerfID}"
ItemsSource="{Binding Source={StaticResource performanceItemsource}}"/>
The Source for the CollectionViewSource is:
public List<MSDExportProxy> Performances
{
get
{
if (Portfolio != null)
{
return (from a in Portfolio.Accounts where a.MSDPortfolioID != null select new MSDExportProxy(a))
.Concat<MSDExportProxy>(from g in Portfolio.Groups where g.MSDPortfolioID != null select new MSDExportProxy(g))
.Concat<MSDExportProxy>(from p in new[] { Portfolio } where p.MSDPortfolioID != null select new MSDExportProxy(p))
.ToList<MSDExportProxy>();
}
return new List<MSDExportProxy>();
}
}
The bound property PlanPerfID is a string.
I move between records using a ListBox control. The ComboBox works fine if the previous record had no items in its ComboBox.ItemsSource. If there were any items in the previous record’s ComboBox.ItemsSource then the new record won’t find its matching item in the ItemsSource collection. I’ve tried setting the ItemsSource in both XAML and the code-behind, but nothing changes this odd behavior. How can I get this darn thing to work?
I found a quick and dirty solution to my problem. I just happen to have a public
NotifyPropertyChanged()method on my Report entity and I discovered that if I calledSelectedReport.NotifyPropertyChanged("PlanPerfID")in the Report ListBox’sSelectionChangedevent that it was enough of a jolt to get theComboBoxto re-evaluate and find its matching item in theItemsSource. Yeah, it’s KLUGE…UPDATE: I also wound up needing to add
SelectedReport.NotifyPropertyChanged("Performances")for some situations…UPDATE 2: Okay, turns out the above wasn’t bullet proof and I ran across a situation that broke it so I had to come up with a better workaround:
Altered the
SelectedReportproperty in the Window’s code-behind, adding a private flag (_settingCombos) to keep the Binding from screwing up the bound values until the dust has settled from changin theItemSource:Created a proxy to bind to in the Window code-behind that will refuse to update the property’s value if the
_settingCombosflag istrue:Added an extra Notification in the Report ListBox’s
SelectionChangedevent along with code to reset the_settingCombosflag back tofalse:Bound the
ComboBoxto thePlanPerfID_Proxyproperty (instead of directly to theSelectedReport.PlanPerfIDproperty.Wow, what a hassle! I think that this is simply a case of .NET’s binding logic getting confused by the dynamic nature of the
ComboBox.ItemSource, but this seems to have fixed it. Hope it helps someone else.