开发者

WPF Databinding: Don't overwrite pre-populated values

开发者 https://www.devze.com 2023-03-21 16:24 出处:网络
I have a MenuItem that I\'d like to populate with sub-items.However, I\'d like for it to keep the items it already has:

I have a MenuItem that I'd like to populate with sub-items. However, I'd like for it to keep the items it already has:

<MenuItem Header="_Profiles">
    <MenuItem Header="_New Profile..." />
    <Separator />
    <!-- Databind here! -->
</MenuItem>

However, when I try to use normal declarative开发者_开发技巧 databinding it eliminates the two subitems I've declared.

I'm sure there has to be a way to do this but I can't figure it out and I'm not sure any of my Google searches have been that good; can anyone help?

Thanks!


One approach is to utilize a CompositeCollection:

<MenuItem Header="_File">
    <MenuItem.ItemsSource>
        <CompositeCollection>
            <MenuItem Header="_New" />
            <Separator />
            <CollectionContainer Collection="{Binding MenuItems}" />
            <Separator />
            <MenuItem Header="E_xit" />
        </CompositeCollection>
    </MenuItem.ItemsSource>
</MenuItem>


It will bind all the items in your collection on the MenuItem, so the only way to keep the items there after your collection is loaded/modified is to ensure those static menu items remain in the collection.

One way to do this is to keep two ItemCollections, one of your static values and one of your dynamic values. Bind to the dynamic values. Then before the menu is displayed, merge the collections. That way you don't have to constantly ensure the static values are place as the first two elements of your binded collection.

0

精彩评论

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

关注公众号