I got the menu creation code to work, and then wanted to apply my WPF style instead of typing a bunch of header names in and then maybe having to change them later.
Here is the WPF style:
<Button.ContextMenu>
<ContextMenu>
<ContextMenu.Resources>
<Style x:Key="{x:Type MenuItem}" TargetType="{x:Type MenuItem}" BasedOn="{StaticResource {x:Type MenuItem}}">
<Setter Property="Header" Value="{Binding Command.Name, RelativeSource={RelativeSource Self}}"/>
</Style>
</ContextMenu.Resources>
<MenuItem Command="ApplicationCommands.Cut"/>
</Button.ContextMenu>
<ContextMenu>
<ContextMenu.Resources>
<Style x:Key="{x:Type MenuItem}" TargetType="{x:Type MenuItem}" BasedOn="{StaticResource {x:Type MenuItem}}">
<Setter Property="Header" Value="{Binding Command.Name, RelativeSource={RelativeSource Self}}"/>
</Style>
</ContextMenu.Resources>
<MenuItem Command="ApplicationCommands.Cut"/>
</Button.ContextMenu>
Here is the C# equivalent:
new returnValue = ContextMenu();
//base our style on the current MenuItem Style. No need for null check.
var headerStyle = new Style(typeof(MenuItem), TryFindResource(typeof(MenuItem)) as Style);
var commandNameBinding = new Binding("Command.Name");
commandNameBinding.RelativeSource = RelativeSource.Self;
headerStyle.Setters.Add( new Setter(HeaderedItemsControl.HeaderProperty, commandNameBinding));
returnValue.Resources.Add(typeof(MenuItem), headerStyle);
returnValue.Items.Add(new MenuItem() { Command = ApplicationCommands.Cut });
No comments:
Post a Comment