简体   繁体   中英

How do you add a generic item to a ComboBox bound to a collection in WPF

I have a ComboBox in a WPF application that is bound to an ObservableCollection of Department objects in a C# ViewModel class. I want to use the combo box to filter another collection by department (And indeed it works for that now) The problem is that I want to add an additional option "All" to the top of the list. Is there a correct way to do this. Making a fake department feels wrong in so many ways.

The ComboBox

<ComboBox ItemsSource="{Binding Path=Departments}" 
          SelectedValue="{Binding Path=DepartmentToShow , Mode=TwoWay}" />

You could use a CompositeCollection as the ItemsSource for the ComboBox to include the "All" option. You need to set the Collection property of the CollectionContainer to your "ObservableCollection of Department objects".

<ComboBox >
    <ComboBox.ItemsSource>
        <CompositeCollection>
            <ComboBoxItem>All</ComboBoxItem>
            <CollectionContainer x:Name="departmentCollection"/>
        </CompositeCollection>
    </ComboBox.ItemsSource>
</ComboBox>

Not sure if this will be suitable for your filtering situation however...

Suppose you have a ComboBox named MyCombo , an entity named MyEntity associated with a DomaineService named MyDomainService .

Do not forget

using System.ServiceModel.DomainServices.Client;

and of course the using working well with your Web site of your entity and DomainService

You call a Proc named :

void LoadEntities()
{
    MyDomainService_Context = new MyDomainService();
    EntityQuery<MyEntity > mQuery = null;

    mQuery = from q in _Context.GetMyDomainServiceQuery()
             select q;

    LoadOperation<MyEntity > loadOpLoadEntities = _Context.Load(mQuery, LoadOpLoadEntitiesCallBack, null);
}

Then in the CallBack function:

void LoadOpLoadEntitiesCallBack(LoadOperation<MyEntity> loadOperation)
{
    if (loadOperation.Entities.Count() > 0)
    {
        List<MyEntity> mList = new List<MyEntity>();
        MyEntity mE = new MyEntity();
        mE.Column1 = -1;
        mE.Column2 = "Default value";
        mList.Add(mE);

        for (int i = 0; i < loadOperation.Entities.Count(); i++)
        {
            mList.Add(loadOperation.Entities.ToList()[i]);
        }

        this.MyCombo.ItemsSource = mList.ToList();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM