开发者

XAML and Binding Submenu items in a ContextMenu?

I have a ContextMenu defined on a Datagrid but want to bind submenu items to a collection on my viewmodel. Can anybody suggest how this should be done?

The following is a simple example of what I'm trying to achieve, BUT I want "Test1", "Test2" to come from a collection on my viewmodel, not hardcoded. I know how to bind my collection to the whole ContextMenu, but not how to bind it to just the one submenu...

<ContextMenu>
    <MenuItem Header="Add to">
        &l开发者_开发问答t;MenuItem Header="Test1" />
        <MenuItem Header="Test2" />
    </MenuItem>
    <MenuItem Header="Remove from All" />
</ContextMenu>

I'm using 3.5 SP1 and the WPF Toolkit.


Guess I should have experimented more. Turns out this was relatively simple:

<my:DataGrid.ContextMenu>
    <ContextMenu>
        <MenuItem Header="Add to" ItemsSource="{Binding MyItems}">
            <MenuItem.ItemTemplate>
                <DataTemplate>
                    <MenuItem CommandTarget="{Binding}" Click="AddClick">
                        <MenuItem.Header>
                            <TextBlock>
                            <TextBlock.Text><Binding StringFormat="Add to {0}" /></TextBlock.Text>
                            </TextBlock>
                        </MenuItem.Header>
                    </MenuItem>
                </DataTemplate>
            </MenuItem.ItemTemplate>
        </MenuItem>
        <MenuItem Header="Remove from All" />
    </ContextMenu>
</my:DataGrid.ContextMenu>


There is a bug when using MenuItem.ItemTemplate. The color when do mouse over on the sub menu make user misunderstand that they can click to select the menu but it doesn't work for all area even if it's highlighted. See the picture

XAML and Binding Submenu items in a ContextMenu?

Then I used this code instead and it worked fine for me.

<ContextMenu>
    <MenuItem Header="Add to" ItemsSource="{Binding MyItems}" 
              DisplayMemberPath="{Binding ItemName}">
       <MenuItem.ItemContainerStyle>
           <Style>
              <EventSetter Event="MenuItem.Click" Handler="Menu_Click"/>
           </Style>
        </MenuItem.ItemContainerStyle>
    </MenuItem>
    <MenuItem Header="Remove from All" />
</ContextMenu>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜