How to Get contextmenu object in opening event - wpf

When contextmenu is opening, I want to fill a textbox with source control's information, for example its name and so on, for viewing and editing purpose.
But I however cannot access the opening contextmenu anyway.
Maybe this is because my less understanding of control's xaml style.
The following is my xaml:
the context menu part: I want to fill the TextBox when contextmenu is opening.
<ContextMenu x:Key="VacUnitContextMenu" >
<MenuItem Header="Property">
<MenuItem>
<MenuItem.Header>
<StackPanel Orientation="Horizontal">
<Label Content="Name" />
<TextBox Width="60" Name="VacName" Margin="2,0" />
</StackPanel>
</MenuItem.Header>
</MenuItem>
<MenuItem Header="Get" Command="{x:Static s:DesignerCanvas.VacUnitNameGet}"/>
</MenuItem>
<MenuItem Header="X">
<MenuItem Header="TEST" Command="{x:Static s:DesignerCanvas.XTest}">
<MenuItem.Icon>
<Image Source="Images/SendToBack.png" Width="16"/>
</MenuItem.Icon>
</MenuItem>
</MenuItem>
</ContextMenu>
the context menu is used in this way:
<!-- VacUnit Style -->
<Style TargetType="{x:Type s:VacUnit}" >
<Setter Property="MinWidth" Value="10"/>
<Setter Property="MinHeight" Value="10"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type s:VacUnit}">
<Grid DataContext="{Binding RelativeSource={RelativeSource TemplatedParent}}"
ContextMenu="{StaticResource VacUnitContextMenu}"
>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
I use conextmenuopening event, and try to fill the textbox there,
How to: Handle the ContextMenuOpening Event
But I cannnot get the contextmenu, it is null:
FrameworkElement fe = e.Source as FrameworkElement;
ContextMenu cm = fe.ContextMenu;
Many thanks in advance.
Ting

Getting a reference to the ContextMenu should be easy provided that you handle the ContextMenuOpening event for the Grid in the ControlTemplate:
<ControlTemplate TargetType="{x:Type s:VacUnit}">
<Grid DataContext="{Binding RelativeSource={RelativeSource TemplatedParent}}"
ContextMenu="{StaticResource VacUnitContextMenu}"
ContextMenuOpening="Grid_ContextMenuOpening">
</Grid>
</ControlTemplate>
What's a bit trickier is to get a reference to the TextBox. You need to wait until it has been loaded:
private void Grid_ContextMenuOpening(object sender, ContextMenuEventArgs e)
{
Grid grid = (Grid)sender;
ContextMenu cm = grid.ContextMenu;
if (cm != null)
cm.Opened += Cm_Opened;
}
private void Cm_Opened(object sender, RoutedEventArgs e)
{
ContextMenu cm = (ContextMenu)sender;
cm.Opened -= Cm_Opened;
MenuItem header = cm.Items[0] as MenuItem;
MenuItem child = header.Items[0] as MenuItem;
StackPanel sp = child.Header as StackPanel;
(sp.Children[1] as TextBox).Background = Brushes.Yellow;
}

Probably e.Source is not a Grid where the context menu is defined.
You can search parent elements until you will find the element where the context menu is.
private void Xxx_ContextMenuOpening(object sender, ContextMenuEventArgs e)
{
var fe = e.Source as FrameworkElement;
var contextMenu = FindContextMenu(fe);
if(contextMenu != null)
{
// your code
}
}
// helper
private ContextMenu FindContextMenu(FrameworkElement fe)
{
if(fe == null)
{
return null;
}
if(fe.ContextMenu != null)
{
return fe.ContextMenu;
}
else
{
var parent = VisualTreeHelper.GetParent(fe) as FrameworkElement;
return FindContextMenu(parent);
}
}

Related

Handle Events in Custom Control Code Behind

Ok, that probably is a pretty dumb question but I have searched quite a while but could not find a solution for this that works...
I have a Custom control inherited from Control, which shall include code behind automation.
For examble select all text of a controls TextBox when selected, or generate a list of close matches when the content of that TextBox is changed.
public class vokDataGridEdit : Control
{
static vokDataGridEdit()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(vokDataGridEdit), new FrameworkPropertyMetadata(typeof(vokDataGridEdit)));
// Events internal to control (??? found on some how-to's)
EventManager.RegisterClassHandler(typeof(vokDataGridEdit), UIElement.GotKeyboardFocusEvent, new RoutedEventHandler(OnSelectContent), true);
}
// Dependecy Properties ...
// The Event that shall Fire when the TextBox gets Focus / Editing Mode
public static void SelectContent(object sender, RoutedEventArgs e)
{
if (sender is TextBox tb)
{
tb.SelectAll();
}
}
}
And the controls Style Template:
<ResourceDictionary xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ccont = "clr-namespace:App.Controls">
<!-- Default style for the Validation Buttons -->
<Style TargetType="{x:Type ccont:vokDataGridEdit}">
<Setter Property="SnapsToDevicePixels" Value="true" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ccont:vokDataGridEdit}">
<TextBox Text = "{Binding Text, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, RelativeSource={RelativeSource AncestorType=ccont:vokDataGridEdit}}"
BorderThickness = "0"
ContextMenuService.Placement = "Right"
ContextMenuService.PlacementTarget = "{Binding Path=., RelativeSource={RelativeSource Self}}"
GotKeyboardFocus = "SelectContent">
<TextBox.ContextMenu>
<ContextMenu>
<ContextMenu.Template>
<ControlTemplate>
<Border CornerRadius = "5"
Background = "LightGray"
BorderThickness = "1"
BorderBrush = "Gray"
Padding = "2">
<StackPanel Orientation="Vertical">
<!-- Title -->
<TextBlock Text="Test" />
<!-- TODO: List of matches -->
<TextBox Text = "{Binding Text, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, RelativeSource={RelativeSource AncestorType=ccont:vokDataGridEdit}}"
BorderThickness = "0" />
</StackPanel>
</Border>
</ControlTemplate>
</ContextMenu.Template>
</ContextMenu>
</TextBox.ContextMenu>
</TextBox>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
Question 1: How can I bind the event SelectContent (to select all TextBox content when it get focus, nb: it is part of a DataGrid for the CellEditingTemplate) to GotKeyboardFocus? Events are normaly fine in the Apps code, but for the Custom Control they do not work as there is no "Code Behind" really for the Style...
Question 2: Assuming I have a dependency Property containing an array of words. Based on the content of the TextBox, I would like to select a few words from the Array in the Dependency Property and pass them to a ListBox in the Custom Control (the Content of the ListBox shall only be managed by the Custom Control, not by anyone using that control. Is there a prefered/canonical MVVM schema on how to implement this?
Usually you should post only one question, not multiple. Regarding first one you can use EventSetter e.g. in implicit Style in UserControl's resources:
<Style TargetType="TextBox">
<EventSetter Event="GotKeyboardFocus" Handler="SelectContent"/>
</Style>
Regarding second question - implement a property, which is subset of your list and do update it accordingly e.g. if dependency property was changed(see property changed callback) or some another values were changed which the subset depends on.
Alternatively you could use a behavior for the TextBox and handle events you need there. See e.g. select all behavior:
public class SelectAllBehavior : Behavior<TextBox>
{
private bool _doSelectAll = false;
protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.GotFocus += AssociatedObject_GotFocus;
AssociatedObject.PreviewMouseUp += AssociatedObject_MouseUp;
AssociatedObject.PreviewMouseDown += AssociatedObject_MouseDown;
}
private void AssociatedObject_MouseUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
if (_doSelectAll)
{
AssociatedObject.Dispatcher.BeginInvoke((Action) (()=>{ AssociatedObject.SelectAll(); }));
}
_doSelectAll = false;
}
private void AssociatedObject_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
_doSelectAll = !AssociatedObject.IsFocused;
}
private void AssociatedObject_GotFocus(object sender, System.Windows.RoutedEventArgs e)
{
AssociatedObject.SelectAll();
}
protected override void OnDetaching()
{
AssociatedObject.GotFocus -= AssociatedObject_GotFocus;
AssociatedObject.PreviewMouseUp -= AssociatedObject_MouseUp;
AssociatedObject.PreviewMouseDown -= AssociatedObject_MouseDown;
base.OnDetaching();
}
}
Using this behavior in XAML:
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
<TextBox Text="Some text">
<i:Interaction.Behaviors>
<local:SelectAllBehavior/>
</i:Interaction.Behaviors>
</TextBox>
Partial Solution:
Finaly I got event on the direct controls to work (controls in a ContextMenu still don't get EventHandlers...).
Apparently the point was using GetTemplateChild() in order to get the TextBox by name, and then associate the Event handlers:
<ResourceDictionary xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ccont = "clr-namespace:App.Controls">
<!-- Default style for the Validation Buttons -->
<Style TargetType="{x:Type ccont:vokDataGridEdit}">
<Setter Property="SnapsToDevicePixels" Value="true" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ccont:vokDataGridEdit}">
<TextBox Text = "{Binding Text, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, RelativeSource={RelativeSource AncestorType=ccont:vokDataGridEdit}}"
BorderThickness = "0"
ContextMenuService.Placement = "Right"
ContextMenuService.PlacementTarget = "{Binding Path=., RelativeSource={RelativeSource Self}}"
x:Name = "TextBox">
<TextBox.ContextMenu>
<ContextMenu x:Name="Menu">
<ContextMenu.Template>
<ControlTemplate>
<Border CornerRadius = "5"
Background = "LightGray"
BorderThickness = "1"
BorderBrush = "Gray"
Padding = "2">
<StackPanel Orientation="Vertical">
<!-- Title -->
<TextBlock Text="Test" x:Name = "Test" />
<!-- TODO: List of matches -->
<TextBox Text = "{Binding Text, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, RelativeSource={RelativeSource AncestorType=ccont:vokDataGridEdit}}"
BorderThickness = "0" />
</StackPanel>
</Border>
</ControlTemplate>
</ContextMenu.Template>
</ContextMenu>
</TextBox.ContextMenu>
</TextBox>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
And Code (Dependency Properties not shown):
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
namespace App.Controls
{
/// <summary>
/// DataGrid Edit control (see: https://www.c-sharpcorner.com/article/wpf-routed-events/ for RoutedEvents)
/// </summary>
public class vokDataGridEdit : Control
{
static vokDataGridEdit()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(vokDataGridEdit), new FrameworkPropertyMetadata(typeof(vokDataGridEdit)));
}
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
// Demo purpose only, check for previous instances and remove the handler first
if (this.GetTemplateChild("TextBox") is TextBox button)
{
button.PreviewMouseLeftButtonDown += this.SelectContentPreparation;
button.GotKeyboardFocus += this.SelectContent;
button.MouseDoubleClick += this.SelectContent;
//button.GotFocus += this.SelectContent;
}
}
/// <summary>
/// Prepare the Control to ensure it has focus before subsequent event fire
/// </summary>
private void SelectContentPreparation(object sender, MouseButtonEventArgs e)
{
if (sender is TextBox tb)
{
if (!tb.IsKeyboardFocusWithin)
{
e.Handled = true;
tb.Focus();
}
}
}
private void SelectContent(object sender, RoutedEventArgs e)
{
if (sender is TextBox tb)
{
e.Handled = true;
tb.SelectAll();
}
}
}
}

Setting SelectedItem in ListView when user clicks in ItemTemplate Textbox

I have the following ListView (simplified):
<ListView Name="lvwNotes" KeyUp="lvwNotes_KeyUp">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical">
<DockPanel Background="LightGray">
<TextBlock DockPanel.Dock="Right" Text="{Binding Path=Author}" />
<TextBlock Text="{Binding Path=Timestamp}" />
</DockPanel>
<TextBox Text="{Binding Path=Text}"
GotFocus = "lvwNotes_TextBox_GotFocus"
TextWrapping="Wrap" />
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
Changing the selected item through a click only works when the user clicks on the DockPanel with the TextBlocks, but not on clicking the TextBox. What I want to achieve is to set the selected item to that one containing the TextBox into which the user clicked.
I managed to get through to the ListViewItem related to the TextBox:
private void lvwNotes_TextBox_GotFocus(object sender, RoutedEventArgs e) {
DependencyObject o = Tools.GetAncestorByType((DependencyObject)sender, typeof(ListViewItem));
if (!o.Equals(null)) {
// code to select this ListViewItem
}
}
But setting
lvwNotes.SelectedIten = o ;
remains without effect. I've tried also some tricks with Dispatcher.BeginInvoke, but to be honest, I don't exactly know what I'm doing there.
Add this to your code
<ListView.Resources>
<Style TargetType="ListViewItem">
<Style.Triggers>
<Trigger Property="IsKeyboardFocusWithin" Value="True">
<Setter Property="IsSelected" Value="True" />
</Trigger>
</Style.Triggers>
</Style>
</ListView.Resources>
The DataContext unless explicitly changed in the DataTemplate is the current item, hence:
private void lvwNotes_TextBox_GotFocus(object sender, RoutedEventArgs e)
{
var tb = (TextBox)sender;
lvwNotes.SelectedItem = tb.DataContext;
}

WPF: Exception if i add a eventhandler to a MenuItem (in a ListBox)

i wanted a contextmenu for my ListBoxItems.
So i created this:
<ListBox Name="listBoxName">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding UserName}" />
</DataTemplate>
</ListBox.ItemTemplate>
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="ContextMenu">
<Setter.Value>
<ContextMenu>
<MenuItem Header="View" Name="MenuItemView" />
</ContextMenu>
</Setter.Value>
</Setter>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
This works great. I have the contextmenu for all items, but if i want to add a click-eventhandler to the menuitem, like this:
<MenuItem Header="View" Name="MenuItemView" Click="MenuItemView_Click" />
I get a XamlParseException when the window is created.
InnerException:
The Object System.Windows.Controls.MenuItem cannot be converted to type System.Windows.Controls.Grid
It throws only the exception if i add a event-handler. The event-method is empty.
Edit:
Stacktrace of the InnerException:
at
Chat_Client.ChatWindow.System.Windows.Markup.IComponentConnector.Connect(Int32
connectionId, Object target) in
c:\XXX\Chat_Client\ChatWindow.xaml:Row
19.
at
MS.Internal.Xaml.Runtime.ClrObjectRuntime.SetConnectionId(Object
root, Int32 connectionId, Object
instance)
Edit2:
Now i have to get the object I clicked with the contextmenu. First i tried this:
//MenuItem s = sender as MenuItem;
//ContextMenu cm = s.Parent as ContextMenu;
//Popup pu = cm.Parent as Popup;
//object o = pu.Parent;
But the Popup's parent is null.
Then i simply get the selectedItem from the ListBox. This works, but is there no way to get the ListBoxRow of the clicked Contextmenu?
I cannot reproduce your crash with VS2010 and WPF4.
You only need one context menu for all your items so you can extract it to a window resource, for example:
<Window.Resources>
<ContextMenu x:Key="ListBoxItemContextMenu">
<MenuItem Header="View" Name="MenuItemView" Click="MenuItemView_Click"/>
</ContextMenu>
</Window.Resources>
and then change your setter to refer to that one context menu:
<Setter Property="ContextMenu" Value="{StaticResource ListBoxItemContextMenu}"/>
and the event handler then works:
private void MenuItemView_Click(object sender, RoutedEventArgs e)
{
Debug.WriteLine("Clicked!");
}

WPF Context menu on left click

I have a WPF application..In which I have an Image control in Xaml file.
On right click of this image I have a context menu.
I would like to have same to be displayed on "Left click" also.
How do I do this in MVVM way ?
Here is a XAML only solution.
Just add this style to your button.
This will cause the context menu to open on both left and right click. Enjoy!
<Button Content="Open Context Menu">
<Button.Style>
<Style TargetType="{x:Type Button}">
<Style.Triggers>
<EventTrigger RoutedEvent="Click">
<EventTrigger.Actions>
<BeginStoryboard>
<Storyboard>
<BooleanAnimationUsingKeyFrames Storyboard.TargetProperty="ContextMenu.IsOpen">
<DiscreteBooleanKeyFrame KeyTime="0:0:0" Value="True"/>
</BooleanAnimationUsingKeyFrames>
</Storyboard>
</BeginStoryboard>
</EventTrigger.Actions>
</EventTrigger>
</Style.Triggers>
<Setter Property="ContextMenu">
<Setter.Value>
<ContextMenu>
<MenuItem />
<MenuItem />
</ContextMenu>
</Setter.Value>
</Setter>
</Style>
</Button.Style>
</Button>
You can do this by using the MouseDown event of an Image like this
<Image ... MouseDown="Image_MouseDown">
<Image.ContextMenu>
<ContextMenu>
<MenuItem .../>
<MenuItem .../>
</ContextMenu>
</Image.ContextMenu>
</Image>
And then show the ContextMenu in the EventHandler in code behind
private void Image_MouseDown(object sender, MouseButtonEventArgs e)
{
if (e.ChangedButton == MouseButton.Left)
{
Image image = sender as Image;
ContextMenu contextMenu = image.ContextMenu;
contextMenu.PlacementTarget = image;
contextMenu.IsOpen = true;
e.Handled = true;
}
}
You can invent your own DependencyProperty which opens a context menu when image is clicked, just like this:
<Image Source="..." local:ClickOpensContextMenuBehavior.Enabled="True">
<Image.ContextMenu>...
</Image.ContextMenu>
</Image>
And here is a C# code for that property:
public class ClickOpensContextMenuBehavior
{
private static readonly DependencyProperty ClickOpensContextMenuProperty =
DependencyProperty.RegisterAttached(
"Enabled", typeof(bool), typeof(ClickOpensContextMenuBehavior),
new PropertyMetadata(new PropertyChangedCallback(HandlePropertyChanged))
);
public static bool GetEnabled(DependencyObject obj)
{
return (bool)obj.GetValue(ClickOpensContextMenuProperty);
}
public static void SetEnabled(DependencyObject obj, bool value)
{
obj.SetValue(ClickOpensContextMenuProperty, value);
}
private static void HandlePropertyChanged(
DependencyObject obj, DependencyPropertyChangedEventArgs args)
{
if (obj is Image) {
var image = obj as Image;
image.MouseLeftButtonDown -= ExecuteMouseDown;
image.MouseLeftButtonDown += ExecuteMouseDown;
}
if (obj is Hyperlink) {
var hyperlink = obj as Hyperlink;
hyperlink.Click -= ExecuteClick;
hyperlink.Click += ExecuteClick;
}
}
private static void ExecuteMouseDown(object sender, MouseEventArgs args)
{
DependencyObject obj = sender as DependencyObject;
bool enabled = (bool)obj.GetValue(ClickOpensContextMenuProperty);
if (enabled) {
if (sender is Image) {
var image = (Image)sender;
if (image.ContextMenu != null)
image.ContextMenu.IsOpen = true;
}
}
}
private static void ExecuteClick(object sender, RoutedEventArgs args)
{
DependencyObject obj = sender as DependencyObject;
bool enabled = (bool)obj.GetValue(ClickOpensContextMenuProperty);
if (enabled) {
if (sender is Hyperlink) {
var hyperlink = (Hyperlink)sender;
if(hyperlink.ContextMenu != null)
hyperlink.ContextMenu.IsOpen = true;
}
}
}
}
If you want to do this just in Xaml without using code-behind you can use Expression Blend's triggers support:
...
xmlns:i="schemas.microsoft.com/expression/2010/interactivity"
...
<Button x:Name="addButton">
<Button.ContextMenu>
<ContextMenu ItemsSource="{Binding Items}" />
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<ei:ChangePropertyAction TargetObject="{Binding ContextMenu, ElementName=addButton}" PropertyName="PlacementTarget" Value="{Binding ElementName=addButton, Mode=OneWay}"/>
<ei:ChangePropertyAction TargetObject="{Binding ContextMenu, ElementName=addButton}" PropertyName="IsOpen" Value="True"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</Button.ContextMenu>
</Button>
you only need add the code into function Image_MouseDown
e.Handled = true;
Then it will not disappear.
Hey I came across the same problem looking for a solution which I didn't find here.
I don't know anything about MVVM so it's probably not MVVM conform but it worked for me.
Step 1: Give your context menu a name.
<Button.ContextMenu>
<ContextMenu Name="cmTabs"/>
</Button.ContextMenu>
Step 2: Double click the control object and insert this code. Order matters!
Private Sub Button_Click_1(sender As Object, e As Windows.RoutedEventArgs)
cmTabs.StaysOpen = True
cmTabs.IsOpen = True
End Sub
Step 3: Enjoy
This will react for left & right click. It's a button with a ImageBrush with a ControlTemplate.
you can bind the Isopen Property of the contextMenu to a property in your viewModel like "IsContextMenuOpen".
but the problem is your can't bind directly the contextmenu to your viewModel because it's not a part of your userControl hiarchy.So to resolve this you should bing the tag property to the dataontext of your view.
<Image Tag="{Binding DataContext, ElementName=YourUserControlName}">
<ContextMenu IsOpen="{Binding PlacementTarget.Tag.IsContextMenuOpen,Mode=OneWay}" >
.....
</ContextMenu>
<Image>
Good luck.
Interactivity is old and not support any more. The new approach for the implementation is:
xmlns:b="http://schemas.microsoft.com/xaml/behaviors"
<Button x:Name="ConvertVideoButton">
<Button.ContextMenu>
<ContextMenu VerticalContentAlignment="Top" >
<MenuItem Header="Convert 1" Command="{Binding ConvertMkvCommand}" />
<MenuItem Header="Convert 2" Command="{Binding ConvertMkvCommand}" />
</ContextMenu>
</Button.ContextMenu>
<b:Interaction.Triggers>
<b:EventTrigger EventName="Click">
<b:ChangePropertyAction TargetObject="{Binding ContextMenu, ElementName=ConvertVideoButton}" PropertyName="PlacementTarget" Value="{Binding ElementName=ConvertVideoButton, Mode=OneWay}"/>
<b:ChangePropertyAction TargetObject="{Binding ContextMenu, ElementName=ConvertVideoButton}" PropertyName="IsOpen" Value="True"/>
</b:EventTrigger>
</b:Interaction.Triggers>
</Button>
XAML
<Button x:Name="b" Content="button" Click="b_Click" >
<Button.ContextMenu >
<ContextMenu >
<MenuItem Header="Open" Command="{Binding OnOpen}" ></MenuItem>
<MenuItem Header="Close" Command="{Binding OnClose}"></MenuItem>
</ContextMenu>
</Button.ContextMenu>
</Button>
C#
private void be_Click(object sender, RoutedEventArgs e)
{
b.ContextMenu.DataContext = b.DataContext;
b.ContextMenu.IsOpen = true;
}

How to get a group of toggle buttons to act like radio buttons in WPF?

I have a group of buttons that should act like toggle buttons, but also as radio buttons where only one button can be selected / pressed down at a current time. It also need to have a state where none of the buttons are selected / pressed down.
The behavior will be kind of like Photoshop toolbar, where zero or one of the tools are selected at any time!
Any idea how this can be implemented in WPF?
This is easiest way in my opinion.
<RadioButton Style="{StaticResource {x:Type ToggleButton}}" />
Enjoy!
-- Pricksaw
The easiest way is to style a ListBox to use ToggleButtons for its ItemTemplate
<Style TargetType="{x:Type ListBox}">
<Setter Property="ListBox.ItemTemplate">
<Setter.Value>
<DataTemplate>
<ToggleButton Content="{Binding}"
IsChecked="{Binding IsSelected, Mode=TwoWay, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBoxItem}}}"
/>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
Then you can use the SelectionMode property of the ListBox to handle SingleSelect vs MultiSelect.
<RadioButton Content="Point" >
<RadioButton.Template>
<ControlTemplate>
<ToggleButton IsChecked="{Binding IsChecked, RelativeSource={RelativeSource TemplatedParent}, Mode=TwoWay}"
Content="{Binding Content, RelativeSource={RelativeSource TemplatedParent}, Mode=TwoWay}"/>
</ControlTemplate>
</RadioButton.Template>
</RadioButton>
it works for me, enjoy!
you could always use a generic event on the Click of the ToggleButton that sets all ToggleButton.IsChecked in a groupcontrol(Grid, WrapPanel, ...) to false with the help of the VisualTreeHelper; then re-check the sender.
Or something in the likes of that.
private void ToggleButton_Click(object sender, RoutedEventArgs e)
{
int childAmount = VisualTreeHelper.GetChildrenCount((sender as ToggleButton).Parent);
ToggleButton tb;
for (int i = 0; i < childAmount; i++)
{
tb = null;
tb = VisualTreeHelper.GetChild((sender as ToggleButton).Parent, i) as ToggleButton;
if (tb != null)
tb.IsChecked = false;
}
(sender as ToggleButton).IsChecked = true;
}
you can put grid with radiobuttons in it, and create button like template for raduiobuttons. than just programmaticaly remove check if you don't want buttons to be toggled
You can also try System.Windows.Controls.Primitives.ToggleButton
<ToggleButton Name="btnTest" VerticalAlignment="Top">Test</ToggleButton>
Then write code against the IsChecked property to mimick the radiobutton effect
private void btnTest_Checked(object sender, RoutedEventArgs e)
{
btn2.IsChecked = false;
btn3.IsChecked = false;
}
I did this for RibbonToggleButtons, but maybe it's the same for regular ToggleButtons.
I bound the IsChecked for each button to a "mode" enum value using EnumToBooleanConverter from here How to bind RadioButtons to an enum? (Specify the enum value for this button using the ConverterParameter. You should have one enum value for each button)
Then to prevent unchecking a button that's already checked, put this in your code behind for the Click event for each of the RibbonToggleButtons:
private void PreventUncheckRibbonToggleButtonOnClick ( object sender, RoutedEventArgs e ) {
// Prevent unchecking a checked toggle button - so that one always remains checked
// Cancel the click if you hit an already-checked button
var button = (RibbonToggleButton)sender;
if( button.IsChecked != null ) { // Not sure why checked can be null but that's fine, ignore it
bool notChecked = ( ! (bool)button.IsChecked );
if( notChecked ){ // I guess this means the click would uncheck it
button.IsChecked = true;
}
}
}
To help people like Julian and me (two minutes ago...). You can derive from the RadioButton like this.
class RadioToggleButton : RadioButton
{
protected override void OnToggle()
{
if (IsChecked == true) IsChecked = IsThreeState ? (bool?)null : (bool?)false;
else IsChecked = IsChecked.HasValue;
}
}
Then, you can use it like Uday Kiran suggested...
<Window x:Class="Sample.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:Sample"
Title="MainWindow" Height="600" Width="600">
<StackPanel>
<local:RadioToggleButton Content="Button" Style="{StaticResource {x:Type ToggleButton}}" />
</StackPanel>
</Window>
This method allows only one ToggleButton to be Checked at a time, and it also allows UnChecking.
I took a few piece of the answers and added some extra code. Now you can have different groups of toggle buttons which act like one toggle button:
<UserControl.Resources>
<Style x:Key="GroupToggleStyle" TargetType="ToggleButton">
<Style.Triggers>
<MultiDataTrigger>
<MultiDataTrigger.Conditions>
<Condition Binding="{Binding GroupName, RelativeSource={RelativeSource Self}}" Value="Group1"/>
<Condition Binding="{Binding BooleanProperty}" Value="true"/>
</MultiDataTrigger.Conditions>
<MultiDataTrigger.Setters>
<Setter Property="IsChecked" Value="true"/>
</MultiDataTrigger.Setters>
</MultiDataTrigger>
</Style.Triggers>
</Style>
</UserControl.Resources>
And the different groups of radio buttons which look like toggle buttons:
<Radio Button GroupName="Group1" Style="{StaticResource {x:Type ToggleButton}}">
<Radio Button GroupName="Group1" Style="{StaticResource {x:Type ToggleButton}}">
<Radio Button GroupName="Group2" Style="{StaticResource {x:Type ToggleButton}}">
<Radio Button GroupName="Group3" Style="{StaticResource {x:Type ToggleButton}}">
One simplistic implementation could be where you maintain a flag in your code behind such as:
ToggleButton _CurrentlyCheckedButton;
Then assign a single Checked event handler to all your context ToggleButtons:
private void ToggleButton_Checked(object sender, RoutedEventArgs e)
{
if (_CurrentlyCheckedButton != null)
_CurrentlyCheckedButton.IsChecked = false;
_CurrentlyCheckedButton = (sender as ToggleButton);
}
And, a single Unchecked event handler:
private void ToggleButton_Unchecked(object sender, RoutedEventArgs e)
{
if (_CurrentlyCheckedButton == (sender as ToggleButton))
_CurrentlyCheckedButton = null;
}
This way you can have the 'zero or one' selection you desire.

Resources