开发者

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

开发者 https://www.devze.com 2022-12-18 12:12 出处:网络
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 c开发者_高级运维ollection b

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 c开发者_高级运维ollection 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();
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消