Get focused MenuItem in submenu WPF

╄→гoц情女王★ 提交于 2019-12-20 03:06:58

问题


I'm writing an application with menu containing submenus. Also I have a StatusBar where I want to display information about focused MenuItem when user navigates in menu with keyboard. I tried to handle GotFocus event from each MenuItem and change StatusBar's content to sender's Tag, but it works only with MenuItem 1, not with 1.1 and 2.2.

XAML:

<Menu Height="23" x:Name="mainMenu">
    <MenuItem Header="Header1" Tag="Info1" GotFocus="MenuItem_GotFocus_1">
        <MenuItem Header="Header1.1" Tag="Info1.1" GotFocus="MenuItem_GotFocus_1"/>
        <MenuItem Header="Header1.2"  Tag="Info1.1" GotFocus="MenuItem_GotFocus_1"/>
        ...
    </MenuItem>
    ...
</Menu>

C#:

private void MenuItem_GotFocus_1(object sender, RoutedEventArgs e)
{
    statusBarItem.Content = (sender as FrameworkElement).Tag;
}

How can I display info about submenu's focused items? Maybe are there other ways to do it?

Thanks, Aleksandr.


回答1:


Not sure if it applies to what you need exactly but I think it's what you need...

It's always best to bind to view-model - and then you can expose that 'status' at some other place by simply binding to it...

In case of IsFocused (If you're talking about the standard WPF menu items) there is a slight problem binding to it, as it's a read-only so binding fails with something like
http://meleak.wordpress.com/2011/08/28/onewaytosource-binding-for-readonly-dependency-property/
(that's also a good example of this solution, similar just for ActiveWidth/Height)

<TreeView.ItemContainerStyle>
<Style TargetType="{x:Type TreeViewItem}">
    <Setter Property="IsExpanded" Value="{Binding IsExpanded, Mode=TwoWay}" />
    <Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}" />
    <Setter Property="pb:PushBindingManager.StylePushBindings">
            <Setter.Value>
    <pb:PushBindingCollection>
    <pb:PushBinding TargetProperty="IsFocused" Path="IsFocused"/>
    </pb:PushBindingCollection>
            </Setter.Value>
    </Setter>

You can download the project/lib to support that from the link in the article above (PushBindingManager) Put something like xmlns:pb="clr-namespace:PushBindingExtension;assembly=some-assembly" (I have it copied, integrated so I don't have the exact source/naming here).

And you should be set to go. Just make IsFocused in your view-model, bind the menu to it - and then put up that whatever item is focused at the status. There is some 'leg work' required here to get this going but pretty minimal.

Hope this helps

NOTE: use the other link for download (i.e. http://dl.dropbox.com/u/39657172/Blog/PushBindingInStyleDemo.zip)
(that one contains the StylePushBindings which you need, for styles.



来源:https://stackoverflow.com/questions/15367161/get-focused-menuitem-in-submenu-wpf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!