0
votes

I have a databound combo box that lists Financial Years. The user selects a value from this combo and a value from a 'Client' combo box which then selects that client's report for that financial year for processing by the user. Although processing a historical document is possible, the default use case is to process a report from the just finished financial year, so I would like to set the Combo box to default to (currently) 2011/2012 which is a string property of the FinancialYear entity.

My xaml:

<ComboBox Canvas.Left="353" 
          Canvas.Top="18" 
          Height="23" 
          Name="cboFinancialYear"
          Width="120" 
          DisplayMemberPath="FinancialYear1" 
          ItemsSource="{Binding}" 
SelectedValuePath="FinancialYearID" />;

The Window_Loaded method in my code behind:

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    String thisYear = MainViewModel.GetCurrentFinancialYear();
    lGFinanceEntities = new LGFinanceEntities();
    // Load data into FinancialYears. You can modify this code as needed.
    CollectionViewSource financialYearsViewSource = ((CollectionViewSource)(this.FindResource("financialYearsViewSource")));
    ObjectQuery<FinancialYear> financialYearsQuery = this.GetFinancialYearsQuery(lGFananceEntities);
     financialYearsViewSource.Source = financialYearsQuery.Execute(System.Data.Objects.MergeOption.AppendOnly);
     cboFinancialYear.SelectedItem = thisYear;
}

However this doesn't seem to have any effect, and the selected item in the combo box is the first year in the FinancialYear table.

Can anybody point out what I've done wrong? I've looked around, but most of the default value implementations in combo boxes seem to be of the 'Select a year' sort as instruction text, whereas I want to actually select a default value.

2
what type your ItemsSource is?gaurawerma
@gaurawerma hmmm, interesting. xaml should have a Source attribute in there. I have fixed it to below, but still not working: <ComboBox Canvas.Left="353" Canvas.Top="18" Height="23" Name="cboFinancialYear" Width="120" DisplayMemberPath="FinancialYear1" ItemsSource="{Binding Source={StaticResource financialYearsViewSource}}" SelectedValuePath="FinancialYearID" /> but it still doesn't workmcalex
I meant what is the type of the entity in your ItemsSourcegaurawerma
is a FinancialYear. In the window resources xaml: <CollectionViewSource x:Key="financialYearsViewSource" d:DesignSource="{d:DesignInstance model:FinancialYear, CreateList=True}" />mcalex
@eticallogics: still working on that mvvm thing. I have code in my xaml code behind at present. (i'm new)mcalex

2 Answers

1
votes

SelectedItem has a reference to an object of the ItemsSource. You cannot set SelectedItem to a string if your ItemsSource is of IEnumerable<FinancialYear> type.

0
votes

Set

cboFinancialYear.SelectedValue=thisYear.FinancialYearID;

Use SelectedValue instead of SelectedItem, I hope this will help.