Editing a local resource's visibility in codebehind - c#

I am fairly new to WPF and have struggled trying to find an answer to this so maybe I am going about it the wrong way.
I have a ContextMenu that I wish to use multiple places so I have it defined as a Resource:
<Window.Resources>
<ContextMenu x:Key="MainContextMenu">
<MenuItem Header="Select All" Click="SelectAllButton_Click"/>
<MenuItem Header="Clear All" Click="ClearAllButton_Click"/>
<MenuItem Header="Export" Click="ExportButton_Click" Name="ExportCM"/>
<MenuItem Header="Priority" Click="PriorityButton_Click" Name="PriorityCM"/>
<MenuItem Header="Cancel" Click="CancelButton_Click" Name="CancelCM"/>
<MenuItem Header="Reallocate" Click="ReallocateButton_Click" Name="ReallocateCM"/>
<MenuItem Header="Release" Click="ReleaseButton_Click" Name="ReleaseCM"/>
<MenuItem Header="Hazard" Click="HazardButton_Click" Name="HazardCM"/>
<MenuItem Header="Reset" Click="ResetButton_Click" Name="ResetCM"/>
</ContextMenu>
</Window.Resources>
I also have a Menu with items with identical headers and click handlers but the Menu is not a resource since I only needed to place it once. With the Menu I am able to edit the visibility of certain MenuItems in codebehind. I would like to be able to do the same to my ContextMenu.
How can I access an individual ContextMenu MenuItem and set its visibility in code behind if my ContextMenu is a locally defined static resource?

You're looking for Custom Controls in WPF. You can extend a WPF control where you can add all your Menus / Menus Items and handle them as objects using XAML.
http://wpftutorial.net/HowToCreateACustomControl.html
After doing that, inside the Window you want to use your custom Menu, you need to add the namespace like in:
xmlns:controls="clr-namespace:YourProject.YourControl"
And then you can use your menu like this:
<controls:YourControl>
Also take a look at DataTemplates.

ContextMenu ctxmenu = (ContextMenu)this.Resources["MainContextMenu"];
And if you assign this context menu to say Button:Btn1, then Btn1.ContextMenu will give you the context menu of button Btn1.
To access a particular menuitem, you have btn1.ContextMenu.Items collections to play with.

Related

Remove checkmark from MenuItems?

I have a context menu that appears when a user right clicks which contains two menu items. The first item has a checkmark instead of the icon, and then a checkmark is placed on whichever one is clicked the next time the user right clicks. I have both IsCheckable and IsChecked set to 'False', but the checkmark still appears. Not sure what I'm doing wrong, any ideas?
This is the first time I right click, I don't want that check mark there.
This is what shows if I selected "add waypoint" the first time, and right clicked again. It should show this every time, but if I ever click "add known object", the checkmark always appears.
<ContextMenu Name="nodeContextMenu" >
<MenuItem x:Name="ko" IsCheckable="False" IsChecked="False" Header="Add Known Object" Click="Ko_Click" >
<MenuItem.Icon>
<Image Source="ko.png" Height="7.5" Width="7.5" />
</MenuItem.Icon>
</MenuItem>
<MenuItem x:Name="wa" IsCheckable="False" IsChecked="False" Header="Add Waypoint" Click="Wa_Click" >
<MenuItem.Icon>
<Image Source="w.png" Height="7.5" Width="7.5" />
</MenuItem.Icon>
</MenuItem>
</ContextMenu>
I found various elaborate WPF solutions for getting rid of the menu item checkmark to be really painful, so I ditched them all. Instead I solved it in a very simple way by having two menu items for what is effectively one menu item at runtime, and use Visibility=Collapsed to alternate between the two at runtime. This is incredibly simple whether you use bindings or events.
I used to have these menuitems as radio buttons, and had a method related to the radio buttons that did a function using the .IsChecked method. I had forgotten about that and it kept the first item checked every time. So I just got rid of it and it works fine. The snippet of code causing it is below:
knownObjectMenuItem.IsChecked = //random stuff

Context Menu Style not applied until right click

I have a context menu attached to a button on a toolbar on one of my controls in WPF (.NET 4.0). The context menu has a style assigned to it in the XAML that defines the context menu. Left clicking on the button opens the button's context menu if it isn't opened already.
Here's the relevant XAML:
<Button x:Name="fileButton" Foreground="White" Margin="7, 0, -3, 0" VerticalAlignment="Stretch" MaxHeight="70" MaxWidth="78" MinHeight="55" MinWidth="62" Style="{DynamicResource ImageButton}" utils:WpfImageUtil.Image="{StaticResource fileButton}" Template="{DynamicResource GlassButton}" Content="File" Visibility="Visible" Click="fileButton_Click">
<Button.ContextMenu>
<ContextMenu Style="{DynamicResource ContextMenuStyle}">
<MenuItem x:Name="saveMenuItem" Header="Save" Click="saveMenuItem_Click" Style="{DynamicResource MenuItemStyle}" />
<MenuItem x:Name="saveDrawingMenuItem" Header="Save Drawing" Click="saveMenuItem_Click" Style="{DynamicResource MenuItemStyle}" />
<MenuItem x:Name="openMenuItem" Header="Open" Style="{DynamicResource MenuItemStyle}">
<MenuItem x:Name="openFromFile" Header="From File" Style="{DynamicResource MenuItemStyle}" />
<MenuItem x:Name="openFromDesktop" Header="From Desktop" Style="{DynamicResource MenuItemStyle}" />
</MenuItem>
<MenuItem x:Name="iconsMenuItem" Header="Icons" ItemsSource="{Binding}" Style="{DynamicResource MenuItemStyle}"/>
<MenuItem x:Name="prefsMenuItem" Header="Preferences" Style="{DynamicResource MenuItemStyle}"/>
</ContextMenu>
</Button.ContextMenu>
</Button>
ContextMenuStyle is defined in a resource dictionary that is properly referenced.
When the context menu is opened with a left click, the style I have defined isn't applied to the menu, as shown below:
However, if the user right-clicks and opens the context menu the traditional way, the style is applied as expected:
Afterwards, left-clicking the button will show the style correctly:
I have been trying to figure this out for some time, but haven't been able to come up with any reason that this issue occurs. It seems like some kind of bug to me, but I'm not entirely sure. I also don't know what happens at the lower level when controls are right-clicked on that would cause the style to get applied correctly.
You should assign ContextMenu Style property in code (FindResource method msdn):
private void fileButton_Click(object sender, RoutedEventArgs e)
{
if (fileButton.ContextMenu.Style == null)
fileButton.ContextMenu.Style = this.FindResource("ContextMenuStyle") as Style;
fileButton.ContextMenu.IsOpen = true;
}
ContextMenu Overview (http://msdn.microsoft.com/en-US/library/ms742558.aspx)
A ContextMenu is attached to a specific control. The ContextMenu
element enables you to present users with a list of items that specify
commands or options that are associated with a particular control, for
example, a Button. Users right-click the control to make the menu
appear. ...
When you right-click on the control, style will be applied to the ContextMenu. So if you want to open ContextMenu in code, you should check if style is equal null and if it's true, you should assign appropriate style.

Is it possible to put a user control into a context menu

I don't know if this is possible but does anyone know if there is a way to put a user control inside a context menu, I have a dialog for adding items to a list but I would like when I click the add button for the control to be displayed in the context menu instead. (dont like having a lot of dialog's in my app).
Here is what I tried but it doesn't work:
<Button Grid.Column="2" Grid.Row="1" Content="Add Item" HorizontalAlignment="Right">
<Button.ContextMenu>
<ContextMenu>
<MenuItem>
<vm:MyControlView/>
</MenuItem>
</ContextMenu>
</Button.ContextMenu>
</Button>
Is there a way to achieve this? (or something similar)
You could try this link, it looks like you might be able to extend ContextMenu like John Dunn did to meet your needs.

Datagrid + Mouse right click event

I have a datagrid and it contains the list of files from the folder. I want to display the default window files right click options in right click on the filename.
That is when ever i right click the filename in the datagrid, a default windows right click pop up should appear.
Can anyone help me to sort this out. The project is in C#.
Thank you.
You should be able to add a Context menu to your data grid. The Context Menu will allow you to add in all the regular Windows right click menu options. The example below only shows copy, cut and paste.
<my:DataGrid
ItemsSource="{Binding}"...>
<my:DataGrid.ContextMenu>
<ContextMenu >
<MenuItem Command="Cut" />
<MenuItem Command="Copy" />
<MenuItem Command="Paste" />
</ContextMenu>
</my:DataGrid.ContextMenu>
</my:DataGrid>
You are able to add icons to the menu options as well if you'd like by writing the menu items more like this.
<MenuItem Command="Paste">
<MenuItem.Icon>
<Image Source="Images/paste.png" />
</MenuItem.Icon>
</MenuItem>

How are DynamicResources built and their use in contextmenus

Are dynamic resources truly dynamic? If I define a DynamicResource, I realise that an expression is created (where?) that is not translated into a resource until runtime, however, What I do not understans is whether this dynamicresouce, once built, is now "Static"
For instance, if I create a context menu via a dynamicresource, are the menuitems which are created at runtime on access then static, even if they are bound?
If so, how can i create a dynamic context menu in XAML?
This is a very complex subject because there are so many kinds of dynamism within WPF. I will start with a simple example to help you understand some basic concepts you need, then proceed to explain the various ways in which a ContextMenu can be dynamically updated and/or replaced, and how DynamicResource fits into the picture.
Initial example: Dynamically updating ContextMenu referenced through StaticResource
Let's say you have the following:
<Window>
<Window.Resources>
<ContextMenu x:Key="Vegetables">
<MenuItem Header="Broccoli" />
<MenuItem Header="Cucumber" />
<MenuItem Header="Cauliflower" />
</ContextMenu>
</Window.Resources>
<Grid>
<Ellipse ContextMenu="{StaticResource Vegetables}" />
<TextBox ContextMenu="{StaticResource Vegetables}" ... />
...
</Grid>
</Window>
** Note the use of StaticResource for now.
This XAML will:
Construct a ContextMenu object with three MenuItems and add it to Window.Resources
Construct an Ellipse object with a reference to the ContextMenu
Construct a TextBox object with a reference to the ContextMenu
Since both the Ellipse and the TextBox have references to the same ContextMenu, updating the ContextMenu will change the options available on each. For example the following will add "Carrots" to the menu when a button is clicked.
public void Button_Click(object sender, EventArgs e)
{
var menu = (ContextMenu)Resources["Vegetables"];
menu.Items.Add(new MenuItem { Header = "Carrots" });
}
In this sense every ContextMenu is dynamic: Its items can be modified at any time and the changes will immediately take effect. This is true even when the ContextMenu is actually open (dropped down) on the screen.
Dynamic ContextMenu updated through data binding
Another way in which a single ContextMenu object is dynamic is that it responds to data binding. Instead of setting individual MenuItems you can bind to a collection, for example:
<Window.Resources>
<ContextMenu x:Key="Vegetables" ItemsSource="{Binding VegetableList}" />
</Window.Resources>
This assumes VegetableList is declared as an ObservableCollection or some other type that implements the INotifyCollectionChanged interface. Any changes you make to the collection will instantly update the ContextMenu, even if it is open. For example:
public void Button_Click(object sender, EventArgs e)
{
VegetableList.Add("Carrots");
}
Note that this kind of collection update need not be made in code: You can also bind the vegetable list to a ListView, DataGrid, etc so that changes may be made by the end-user. These changes will also show up in your ContextMenu.
Switching ContextMenus using code
You can also replace the ContextMenu of an item with a completely different ContextMenu. For example:
<Window>
<Window.Resources>
<ContextMenu x:Key="Vegetables">
<MenuItem Header="Broccoli" />
<MenuItem Header="Cucumber" />
</ContextMenu>
<ContextMenu x:Key="Fruits">
<MenuItem Header="Apple" />
<MenuItem Header="Banana" />
</ContextMenu>
</Window.Resources>
<Grid>
<Ellipse x:Name="Oval" ContextMenu="{StaticResource Vegetables}" />
...
</Grid>
</Window>
The menu can be replaced in code like this:
public void Button_Click(object sender, EventArgs e)
{
Oval.ContextMenu = (ContextMenu)Resources.Find("Fruits");
}
Note that instead of modifying the existing ContextMenu we are switching to a completely different ContextMenu. In this situation both ContextMenus are built immediately when the window is first constructed, but the Fruits menu is not used until it is switched.
If you want to avoid constructing the Fruits menu until it was necessary you could construct it in the Button_Click handler instead of doing it in XAML:
public void Button_Click(object sender, EventArgs e)
{
Oval.ContextMenu =
new ContextMenu { ItemsSource = new[] { "Apples", "Bananas" } };
}
In this example, every time you click on the button a new ContextMenu will be constructed and assigned to the oval. Any ContextMenu defined in Window.Resources still exists but is unused (unless another control uses it).
Switching ContextMenus using DynamicResource
Using DynamicResource allows you to switch between ContextMenus without explicitly assigning it code. For example:
<Window>
<Window.Resources>
<ContextMenu x:Key="Vegetables">
<MenuItem Header="Broccoli" />
<MenuItem Header="Cucumber" />
</ContextMenu>
</Window.Resources>
<Grid>
<Ellipse ContextMenu="{DynamicResource Vegetables}" />
...
</Grid>
</Window>
Because this XAML uses DynamicResource instead of StaticResource, modifying the dictionary will update the ContextMenu property of the Ellipse. For example:
public void Button_Click(object sender, EventArgs e)
{
Resources["Vegetables"] =
new ContextMenu { ItemsSource = new[] {"Zucchini", "Tomatoes"} };
}
The key concept here is that DynamicResource vs StaticResource only controls when the dictionary is lookup is done. If StaticResource is used in the above example, assigning to Resources["Vegetables"] will not update the Ellipse's ContextMenu property.
On the other hand, if you are updating the ContextMenu itself (by changing its Items collection or via data binding), it does not matter whether you use DynamicResource or StaticResource: In each case any changes you make to the ContextMenu will be immediately visible.
Updating individual ContextMenu ITEMS using data binding
The very best way to update a ContextMenu based on properties of the item that is right-clicked is to use data binding:
<ContextMenu x:Key="SelfUpdatingMenu">
<MenuItem Header="Delete" IsEnabled="{Binding IsDeletable}" />
...
</ContextMenu>
This will cause the "Delete" menu item to be automatically grayed out unless the item has its IsDeletable flag set. No code is necessary (or even desirable) in this case.
If you want to hide the item instead of simply graying it out, set Visibility instead of IsEnabled:
<MenuItem Header="Delete"
Visibility="{Binding IsDeletable, Converter={x:Static BooleanToVisibilityConverter}}" />
If you want to add/remove items from a ContextMenu based on your data, you can bind using a CompositeCollection. The syntax is a bit more complex, but it is still quite straightforward:
<ContextMenu x:Key="MenuWithEmbeddedList">
<ContextMenu.ItemsSource>
<CompositeCollection>
<MenuItem Header="This item is always present" />
<MenuItem Header="So is this one" />
<Separator /> <!-- draw a bar -->
<CollectionContainer Collection="{Binding MyChoicesList}" />
<Separator />
<MenuItem Header="Fixed item at bottom of menu" />
</CompositeCollection>
</ContextMenu.ItemsSource>
</ContextMenu>
Assuming "MyChoicesList" is an ObservableCollection (or any other class that implements INotifyCollectionChanged), items added/removed/updated in this collection will be immediately visible on the ContextMenu.
Updating individual ContextMenu ITEMS without data binding
When at all possible you should control your ContextMenu items using data binding. They work very well, are nearly foolproof, and greatly simplify your code. Only if data binding can't be made to work does it make sense to use code to update your menu items. In this case you can build your ContextMenu by handling the ContextMenu.Opened event and doing updates within this event. For example:
<ContextMenu x:Key="Vegetables" Opened="Vegetables_Opened">
<MenuItem Header="Broccoli" />
<MenuItem Header="Green Peppers" />
</ContextMenu>
With this code:
public void Vegetables_Opened(object sender, RoutedEventArgs e)
{
var menu = (ContextMenu)sender;
var data = (MyDataClass)menu.DataContext
var oldCarrots = (
from item in menu.Items
where (string)item.Header=="Carrots"
select item
).FirstOrDefault();
if(oldCarrots!=null)
menu.Items.Remove(oldCarrots);
if(ComplexCalculationOnDataItem(data) && UnrelatedCondition())
menu.Items.Add(new MenuItem { Header = "Carrots" });
}
Alternatively this code could simply change menu.ItemsSource if you were using data binding.
Switching ContextMenus using Triggers
Another technique commonly used to update ContextMenus is to use a Trigger or DataTrigger to switch between a default context menu and a custom context menu depending on the triggering condition. This can handle situations where you want to use data binding but need to replace the menu as a whole rather than update parts of it.
Here is an illustration of what this looks like:
<ControlTemplate ...>
<ControlTemplate.Resources>
<ContextMenu x:Key="NormalMenu">
...
</ContextMenu>
<ContextMenu x:Key="AlternateMenu">
...
</ContextMenu>
</ControlTemplate.Resources>
...
<ListBox x:Name="MyList" ContextMenu="{StaticResource NormalMenu}">
...
<ControlTemplate.Triggers>
<Trigger Property="IsSpecialSomethingOrOther" Value="True">
<Setter TargetName="MyList" Property="ContextMenu" Value="{StaticResource AlternateMenu}" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
In this scenario it is still possible to use data binding to control individual items in both NormalMenu and AlternateMenu.
Releasing ContextMenu resources when the menu is closed
If resources used in a ContextMenu are expensive to keep in RAM you may want to release them. If you are using data binding this is likely to happen automatically, as the DataContext is removed when the menu is closed. If you are using code instead you may have to catch the Closed event on the ContextMenu to deallocate whatever you created in response to the Opened event.
Delayed construction of ContextMenu from XAML
If you have a very complex ContextMenu that you want to code in XAML but don't want to load except when it is needed, two basic techniques are available:
Put it in a separate ResourceDictionary. When necessary, load that ResourceDictionary and add it to MergedDictionaries. As long as you used DynamicResource, the merged value will be picked up.
Put it in a ControlTemplate or DataTemplate. The menu will not actually be instantiated until the template is first used.
However neither of these techniques by itself will cause the loading to happen when the context menu is opened - only when the containing template is instantiated or the dictionary is merged. To accomplish that you must use a ContextMenu with an empty ItemsSource then assign the ItemsSource in the Opened event. However the value of the ItemsSource can be loaded from a ResourceDictionary in a separate file:
<ResourceDictionary ...>
<x:Array x:Key="ComplexContextMenuContents">
<MenuItem Header="Broccoli" />
<MenuItem Header="Green Beans" />
... complex content here ...
</x:Array>
</ResourceDictionary>
with this code in the Opened event:
var dict = (ResourceDictionary)Application.LoadComponent(...);
menu.ItemsSource = dict["ComplexMenuContents"];
and this code in the Closed event:
menu.ItemsSource = null;
Actually if you have only a single x:Array, you may as well skip the ResourceDictionary. If your XAML's outermost element is the x:Array the Opened event code is simply:
menu.ItemsSource = Application.LoadComponent(....)
Summary of critical concepts
DynamicResource is used only for switching values based on which resource dictionaries are loaded and what they contain: When updating the contents of the dictionaries, DynamicResource automatically updates the properties. StaticResource only reads them when the XAML is loaded.
No matter whether DynamicResource or StaticResource is used, the ContextMenu is created when the resource dictionary is loaded not when the menu is opened.
ContextMenus are very dynamic in that you can manipulate them using data binding or code and the changes immediately take effect.
In most cases you should update your ContextMenu using data bindings, not in code.
Completely replacing menus can be done with code, triggers, or DynamicResource.
If contents must be loaded into RAM only when the menu is open, they can be loaded from a separate file in the Opened event and cleared out in the Closed event.

Categories

Resources