开发者

WPF: Can't get to original source from ExecutedRoutedEventArgs

I have a problem getting to the original source of a command using ExecutedRoutedEventArgs.

I'm creating a simple splitbutton, in which a menu will appear below a dedicated button, as another button is pressed. When I click a menuitem in the appearing menu a command is fired. This command is registered on the splitbutton. And the idea is to get to the menuitem beeing clicked, by using the ExecutedRoutedEventsArgs.

Ok, now the problem. If I choose to have the popup menu shown by default (IsOpen="True") and I click one of the menuitems I can get to the originalsource (thus the menuitem) from the ExecutedRoutedEventArgs - no problem. However, if I first click the button to show the menu and THEN click on a menuitem, the originalsource of the command will be the button instead of the MenuItem!

Here's the controltemplate for the splitbutton:

<ControlTemplate TargetType="{x:Type usc:SplitButton}">
  <StackPanel Orientation="Horizontal">
    <Button Name="mybutton">
      <StackPanel>
        <Popup usc:SplitButton.IsPopup="True" IsOpen="True" Name="myPopup" PlacementTarget="{Binding ElementName=mybutton}" StaysOpen="False" Placement="Bottom">
        <Border BorderBrush="Beige" BorderThickness="1">
 开发者_开发技巧         <Menu Width="120">
            <MenuItem Header="item1" Command="usc:SplitButton.MenuItemClickCommand" />
            <MenuItem Header="item2" />
            <MenuItem Header="item3" />
           </Menu>
         </Border>
         </Popup>
         <TextBlock Text="MySplitbutton" />
        </StackPanel>
          </Button> 
      <Button Content="OK" Command="usc:SplitButton.ShowMenuCommand" />
   </StackPanel>
</ControlTemplate>

The OK button fires a ShowMenuCommand on the SplitButton, which sets the IsOpen property on the Popup to True.

Any ideas why the OK button (after having activated the menu) is the OriginalSource when a menuitem is clicked?

Thanks.


The solution to this is to use the CommandParameter property. Then you can bind the CommandParameter to the MenuItem itself, and when the Command is executed you can grab the MenuItem off the parameter.

Something like this should work:

<MenuItem Header="item1" 
          Command="usc:SplitButton.MenuItemClickCommand" 
          CommandParameter="{Binding RelativeSource={RelativeSource Self}}"/>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜