1

I am new to WPF - and painfully aware of it. I have unsuccessfully searched for answers to this particular problem and am now seeking advice from my more knowledgeable peers!

The scenario

The application on which I am working allows users to either enter new records into a database, or amend existing ones.

I have a form containing a bound ComboBox. It is populated from the database, which is accessed by a WPF service that exposes a DTO.

From the UI perspective, the form has two modes: 1. enter new record 2. amend existing record

The ComboBox in question appears in both cases, but the requirement is to have fewer options visible when the form is in 'amend' mode.

What I am trying to do is loop through the ComboBox items when the form is in 'amend' mode and remove/hide the options that should not appear.

The XAML

<ComboBox x:Name="RecordType"  Grid.Column="1" Grid.Row="1"  Width="150"  HorizontalAlignment="Left" SelectedValue="{Binding Path=RecordTypeID,TargetNullValue=0}"/>

The code behind - and my (feeble!) attempts so far

foreach (ComboBoxItem item in this.RecordType.Items)
{
    if (IsApplicable(item.Content.ToString()) == false)
    {
        item.Visibility = Visibility.Hidden;
    }
}

(NOTE: IsApplicable() is a simple method that compares the string it receives to a list of the options that are allowed to appear when the form is in 'amend' mode.)

The problem

As I'm sure many of you will already know ... cannot cast object of type DTO to type System.Windows.Controls.ComboBoxItem

The question(s)

Can I get at the string values in this, or a similar way? If so, how, please?

1
  • How are you populating the combobox?
    – alf
    Oct 13, 2011 at 11:38

2 Answers 2

1

Correct way to do this would be to apply Filter on Collection View See Automatically Filtering a ComboBox in WPF

ICollectionView view = CollectionViewSource.GetDefaultView(comboBox.ItemsSource);
view.Filter = IsApplicable
view.Refresh(); // <-- call this whenever you change the view model
1
  • Thanks, Hasan. That worked for me. (p.s. as soon as achieve 15 rep points, I'll come back and vote this up!)
    – Krayg
    Nov 8, 2011 at 11:51
0

It would likely be easier for you if you bound your combobox to an ObservableCollection and then removed the items from the collection when needed.

Here is an example: http://www.tanguay.info/web/index.php?pg=codeExamples&id=304

1
  • Thanks Joe. I did try this, but couldn't get it to work. This is probably more to do with my n00bness than anything else.
    – Krayg
    Nov 8, 2011 at 11:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.