I am trying to create a localizable WPF menu bar with menu items that have keyboard shortcuts - not accelerator keys/mnemonics (usually shown as underlined characters that can be pressed to directly select a menu item when the menu is already open), but keyboard shortcuts (usually combinations of Ctrl + another key) that are displayed right-aligned next to the menu item header.
I am using the MVVM pattern for my application, meaning that I avoid placing any code in code-behind wherever possible and have my view-models (that I assign to the DataContext properties) provide implementations of the ICommand interface that are used by controls in my views.
As a base for reproducing the issue, here is some minimal source code for an application as described:
Window1.xaml
<Window x:Class="MenuShortcutTest.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MenuShortcutTest" Height="300" Width="300">
<Menu>
<MenuItem Header="{Binding MenuHeader}">
<MenuItem Header="{Binding DoSomethingHeader}" Command="{Binding DoSomething}"/>
</MenuItem>
</Menu>
</Window>
Window1.xaml.cs
using System;
using System.Windows;
namespace MenuShortcutTest
{
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
this.DataContext = new MainViewModel();
}
}
}
MainViewModel.cs
using System;
using System.Windows;
using System.Windows.Input;
namespace MenuShortcutTest
{
public class MainViewModel
{
public string MenuHeader {
get {
// in real code: load this string from localization
return "Menu";
}
}
public string DoSomethingHeader {
get {
// in real code: load this string from localization
return "Do Something";
}
}
private class DoSomethingCommand : ICommand
{
public DoSomethingCommand(MainViewModel owner)
{
if (owner == null) {
throw new ArgumentNullException("owner");
}
this.owner = owner;
}
private readonly MainViewModel owner;
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
// in real code: do something meaningful with the view-model
MessageBox.Show(owner.GetType().FullName);
}
public bool CanExecute(object parameter)
{
return true;
}
}
private ICommand doSomething;
public ICommand DoSomething {
get {
if (doSomething == null) {
doSomething = new DoSomethingCommand(this);
}
return doSomething;
}
}
}
}
The WPF MenuItem class has an InputGestureText property, but as described in SO questions such as this, this, this and this, that is purely cosmetic and has no effect whatsoever on what shortcuts are actually processed by the application.
SO questions like this and this point out that the command should be linked with a KeyBinding in the InputBindings list of the window. While that enables the functionality, it does not automatically display the shortcut with the menu item. Window1.xaml changes as follows:
<Window x:Class="MenuShortcutTest.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MenuShortcutTest" Height="300" Width="300">
<Window.InputBindings>
<KeyBinding Key="D" Modifiers="Control" Command="{Binding DoSomething}"/>
</Window.InputBindings>
<Menu>
<MenuItem Header="{Binding MenuHeader}">
<MenuItem Header="{Binding DoSomethingHeader}" Command="{Binding DoSomething}"/>
</MenuItem>
</Menu>
</Window>
I have tried manually setting the InputGestureText property in addition, making Window1.xaml look like this:
<Window x:Class="MenuShortcutTest.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MenuShortcutTest" Height="300" Width="300">
<Window.InputBindings>
<KeyBinding Key="D" Modifiers="Control" Command="{Binding DoSomething}"/>
</Window.InputBindings>
<Menu>
<MenuItem Header="{Binding MenuHeader}">
<MenuItem Header="{Binding DoSomethingHeader}" Command="{Binding DoSomething}" InputGestureText="Ctrl+D"/>
</MenuItem>
</Menu>
</Window>
This does display the shortcut, but is not a viable solution for obvious reasons:
It does not update when the actual shortcut binding changes, so even if the shortcuts are not configurable by users, this solution is a maintenance nightmare.
The text needs to be localized (as e.g. the Ctrl key has different names in some languages), so if any of the shortcuts is ever changed, all translations would need to be updated individually.
I have looked into creating an IValueConverter to use for binding the InputGestureText property to the InputBindings list of the window (there might be more than one KeyBinding in the InputBindings list, or none at all, so there is no specific KeyBinding instance that I could bind to (if KeyBinding even lends itself to being a binding target)). This appears to me like the most desirable solution, because it is very flexible and at the same time very clean (it does not require a plethora of declarations in various places), but on the one hand, InputBindingCollection does not implement INotifyCollectionChanged, thus the binding would not be updated when shortcuts are replaced, and on the other hand, I did not manage to provide the converter with a reference to my view-model in a tidy manner (which it would need to access the localization data). What is more, InputBindings is not a dependency property, so I cannot bind that to a common source (such as a list of input bindings located in the view-model) that the ItemGestureText property could be bound to, as well.
Now, many resources (this question, that question, this thread, that question and that thread point out that RoutedCommand and RoutedUICommand contain a built-in InputGestures property and imply that key bindings from that property are automatically displayed in menu items.
However, using either of those ICommand implementations seems to open a new can of worms, as their Execute and CanExecute methods are not virtual and thus cannot be overridden in subclasses to fill in the desired functionality. The only way to provide that seems to be declaring a CommandBinding in XAML (shown e.g. here or here) that connects a command with an event handler - however, that event handler would then be located in the code-behind, thus violating the MVVM architecture described above.
Trying nonetheless, this means turning most of the aforementioned structure inside-out (which also kind of implies that I need to make my mind up on how to eventually solve the issue in my current, comparably early stage of development):
Window1.xaml
<Window x:Class="MenuShortcutTest.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:MenuShortcutTest"
Title="MenuShortcutTest" Height="300" Width="300">
<Window.CommandBindings>
<CommandBinding Command="{x:Static local:DoSomethingCommand.Instance}" Executed="CommandBinding_Executed"/>
</Window.CommandBindings>
<Menu>
<MenuItem Header="{Binding MenuHeader}">
<MenuItem Header="{Binding DoSomethingHeader}" Command="{x:Static local:DoSomethingCommand.Instance}"/>
</MenuItem>
</Menu>
</Window>
Window1.xaml.cs
using System;
using System.Windows;
namespace MenuShortcutTest
{
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
this.DataContext = new MainViewModel();
}
void CommandBinding_Executed(object sender, System.Windows.Input.ExecutedRoutedEventArgs e)
{
((MainViewModel)DataContext).DoSomething();
}
}
}
MainViewModel.cs
using System;
using System.Windows;
using System.Windows.Input;
namespace MenuShortcutTest
{
public class MainViewModel
{
public string MenuHeader {
get {
// in real code: load this string from localization
return "Menu";
}
}
public string DoSomethingHeader {
get {
// in real code: load this string from localization
return "Do Something";
}
}
public void DoSomething()
{
// in real code: do something meaningful with the view-model
MessageBox.Show(this.GetType().FullName);
}
}
}
DoSomethingCommand.cs
using System;
using System.Windows.Input;
namespace MenuShortcutTest
{
public class DoSomethingCommand : RoutedCommand
{
public DoSomethingCommand()
{
this.InputGestures.Add(new KeyGesture(Key.D, ModifierKeys.Control));
}
private static Lazy<DoSomethingCommand> instance = new Lazy<DoSomethingCommand>();
public static DoSomethingCommand Instance {
get {
return instance.Value;
}
}
}
}
For the same reason (RoutedCommand.Execute and such being non-virtual), I do not know how to subclass RoutedCommand in a way to create a RelayCommand like the one used in an answer to this question based on RoutedCommand, so I do not have to make the detour over the InputBindings of the window - while explicitly reimplementing the methods from ICommand in a RoutedCommand subclass feels like I might be breaking something.
What is more, while the shortcut is automatically displayed with this method as configured in the RoutedCommand, it does not seem to get automatically localized. My understanding is that adding
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("de-de");
System.Threading.Thread.CurrentThread.CurrentUICulture = System.Threading.Thread.CurrentThread.CurrentCulture;
to the MainWindow constructor should make sure that localizable strings supplied by the framework should be taken from the German CultureInfo - however, Ctrl does not change to Strg, so unless I am mistaken about how to set the CultureInfo for framework-supplied strings, this method is not viable anyway if I expect the displayed shortcut to be correctly localized.
Now, I am aware that KeyGesture allows me to specify a custom display string for the keyboard shortcut, but not only is the RoutedCommand-derived DoSomethingCommand class disjoint from all of my instances (from where I could get in touch with the loaded localization) due to the way CommandBinding has to be linked with a command in XAML, the respective DisplayString property is read-only, so there would be no way to change it when another localization is loaded at runtime.
This leaves me with the option to manually dig through the menu tree (EDIT: for the sake of clarification, no code here because I am not asking for this and I know how to do this) and the InputBindings list of the window to check which commands have any KeyBinding instances associated with them, and which menu items are linked to any of those commands, so that I can manually set the InputGestureText of each of the respective menu items to reflect the first (or preferred, by whichever metric I want to use here) keyboard shortcut. And this procedure would have to be repeated every time I think the key bindings may have changed. However, this seems like an extremely tedious workaround for something that is essentially a basic feature of a menu bar GUI, so I'm convinced it cannot be the "correct" way to do this.
What is the right way to automatically display a keyboard shortcut that is configured to work for WPF MenuItem instances?
EDIT: All of the other questions I found dealt with how a KeyBinding/KeyGesture could be used to actually enable the functionality visually implied by InputGestureText, without explaining how to automatically link the two aspects in the described situation. The only somewhat promising question that I found was this, but it has not received any answers in over two years.
I'll start with the warning. It can happen that you will need not only customizable hot keys but the menu itself. So think twice before using InputBindings statically.
There is one more caution concerning InputBindings: they imply that command is tied to the element in window's visual tree. Sometimes you need global hot keys not connected with any particular window.
The above said means that you can make it another way and implement your own application wide gestures processing with correct routing to corresponding commands (don't forget to use weak references to commands).
Nonetheless the idea of gesture aware commands is the same.
public class CommandWithHotkey : ICommand
{
public bool CanExecute(object parameter)
{
return true;
}
public void Execute(object parameter)
{
MessageBox.Show("It Worked!");
}
public KeyGesture Gesture { get; set; }
public string GestureText
{
get { return Gesture.GetDisplayStringForCulture(CultureInfo.CurrentUICulture); }
}
public string Text { get; set; }
public event EventHandler CanExecuteChanged;
public CommandWithHotkey()
{
Text = "Execute Me";
Gesture = new KeyGesture(Key.K, ModifierKeys.Control);
}
}
Simple View Model:
public class ViewModel
{
public ICommand Command { get; set; }
public ViewModel()
{
Command = new CommandWithHotkey();
}
}
Window:
<Window x:Class="CommandsWithHotKeys.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:commandsWithHotKeys="clr-namespace:CommandsWithHotKeys"
Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
<commandsWithHotKeys:ViewModel/>
</Window.DataContext>
<Window.InputBindings>
<KeyBinding Command="{Binding Command}" Key ="{Binding Command.Gesture.Key}" Modifiers="{Binding Command.Gesture.Modifiers}"></KeyBinding>
</Window.InputBindings>
<Grid>
<Menu HorizontalAlignment="Stretch" VerticalAlignment="Top" Height="Auto">
<MenuItem Header="Test">
<MenuItem InputGestureText="{Binding Command.GestureText}" Header="{Binding Command.Text}" Command="{Binding Command}">
</MenuItem>
</MenuItem>
</Menu>
</Grid>
</Window>
Sure, you should somehow load the gestures information from configuration and then init commands with the data.
The next step is keystokes like in VS: Ctrl+K,Ctrl+D, quick search gives this SO question.
If I haven't misunderstood your question try this:
<Window.InputBindings>
<KeyBinding Key="A" Modifiers="Control" Command="{Binding ClickCommand}"/>
</Window.InputBindings>
<Grid >
<Button Content="ok" x:Name="button">
<Button.ContextMenu>
<local:CustomContextMenu>
<MenuItem Header="Click" Command="{Binding ClickCommand}"/>
</local:CustomContextMenu>
</Button.ContextMenu>
</Button>
</Grid>
..with:
public class CustomContextMenu : ContextMenu
{
public CustomContextMenu()
{
this.Opened += CustomContextMenu_Opened;
}
void CustomContextMenu_Opened(object sender, RoutedEventArgs e)
{
DependencyObject obj = this.PlacementTarget;
while (true)
{
obj = LogicalTreeHelper.GetParent(obj);
if (obj == null || obj.GetType() == typeof(Window) || obj.GetType() == typeof(MainWindow))
break;
}
if (obj != null)
SetInputGestureText(((Window)obj).InputBindings);
//UnSubscribe once set
this.Opened -= CustomContextMenu_Opened;
}
void SetInputGestureText(InputBindingCollection bindings)
{
foreach (var item in this.Items)
{
var menuItem = item as MenuItem;
if (menuItem != null)
{
for (int i = 0; i < bindings.Count; i++)
{
var keyBinding = bindings[i] as KeyBinding;
//find one whose Command is same as that of menuItem
if (keyBinding!=null && keyBinding.Command == menuItem.Command)//ToDo : Apply check for None Modifier
menuItem.InputGestureText = keyBinding.Modifiers.ToString() + " + " + keyBinding.Key.ToString();
}
}
}
}
}
I hope this will give you an idea.
This is how it did it:
In the loaded-event of my window I match the Command bindings of the menu items with the Command bindings of all InputBindings, much like ethicallogics's answer, but for a menu bar and it actually compares the Command bindings and not just the value, because that didn't work for me. this code also recurses into submenus.
private void MainWindow_OnLoaded(object sender, RoutedEventArgs e)
{
// add InputGestures to menu items
SetInputGestureTextsRecursive(MenuBar.Items, InputBindings);
}
private void SetInputGestureTextsRecursive(ItemCollection items, InputBindingCollection inputBindings)
{
foreach (var item in items)
{
var menuItem = item as MenuItem;
if (menuItem != null)
{
if (menuItem.Command != null)
{
// try to find an InputBinding with the same command and take the Gesture from there
foreach (KeyBinding keyBinding in inputBindings.OfType<KeyBinding>())
{
// we cant just do keyBinding.Command == menuItem.Command here, because the Command Property getter creates a new RelayCommand every time
// so we compare the bindings from XAML if they have the same target
if (CheckCommandPropertyBindingEquality(keyBinding, menuItem))
{
// let a new Keygesture create the String
menuItem.InputGestureText = new KeyGesture(keyBinding.Key, keyBinding.Modifiers).GetDisplayStringForCulture(CultureInfo.CurrentCulture);
}
}
}
// recurse into submenus
if (menuItem.Items != null)
SetInputGestureTextsRecursive(menuItem.Items, inputBindings);
}
}
}
private static bool CheckCommandPropertyBindingEquality(KeyBinding keyBinding, MenuItem menuItem)
{
// get the binding for 'Command' property
var keyBindingCommandBinding = BindingOperations.GetBindingExpression(keyBinding, InputBinding.CommandProperty);
var menuItemCommandBinding = BindingOperations.GetBindingExpression(menuItem, MenuItem.CommandProperty);
if (keyBindingCommandBinding == null || menuItemCommandBinding == null)
return false;
// commands are the same if they're defined in the same class and have the same name
return keyBindingCommandBinding.ResolvedSource == menuItemCommandBinding.ResolvedSource
&& keyBindingCommandBinding.ResolvedSourcePropertyName == menuItemCommandBinding.ResolvedSourcePropertyName;
}
Do this one time in your Window's code-behind and every menu item has an InputGesture. Just the translation is missing
Based on Pavel Voronin's answer, I created the following. Actually I just created two new UserControls which automatically set Gesture on the command and read it.
class HotMenuItem : MenuItem
{
public HotMenuItem()
{
SetBinding(InputGestureTextProperty, new Binding("Command.GestureText")
{
Source = this
});
}
}
class HotKeyBinding : KeyBinding
{
protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e)
{
base.OnPropertyChanged(e);
if (e.Property.Name == "Command" || e.Property.Name == "Gesture")
{
if (Command is IHotkeyCommand hotkeyCommand)
hotkeyCommand.Gesture = Gesture as KeyGesture;
}
}
}
The used interface
public interface IHotkeyCommand
{
KeyGesture Gesture { get; set; }
}
The Command is pretty much the same, it just implements INotifyPropertyChanged.
So the usage gets a bit cleaner in my opinion:
<Window.InputBindings>
<viewModels:HotKeyBinding Command="{Binding ExitCommand}" Gesture="Alt+F4" />
</Window.InputBindings>
<Menu>
<MenuItem Header="File" >
<viewModels:HotMenuItem Header="Exit" Command="{Binding ExitCommand}" />
</MenuItem>
</Menu>
Related
I have been going through posts for 3 hours now with no resolution. I am new to WPF and created the ComboBox below:
Unfortunately I cannot disable the highlighting of the selected item. Does anyone have a viable solution?
Code:
<StackPanel Grid.Column="1"
Margin="800,0,0,0"
Width="135"
HorizontalAlignment="Right"
VerticalAlignment="Center">
<ComboBox Name="LangComboBox"
IsEditable="True"
IsReadOnly="True"
Text="Select Language">
<ComboBoxItem>English</ComboBoxItem>
<ComboBoxItem>Spanish</ComboBoxItem>
<ComboBoxItem>Both</ComboBoxItem>
</ComboBox>
</StackPanel>
I would like to clarify first of all that mine wants to be constructive answer and want to try to spread the culture of good programming.
We all have always to learn about programming, me too!
If you do not know a topic, it is good practice to study perhaps starting from a good book or from the official documentation of the platform.
That said let's move on to some possible approaches to your problem.
First of all, the fact that the selection in the combobox is that way is due to the basic template of the combobox that I invite you to view: https://msdn.microsoft.com/library/ms752094(v=vs.85).aspx )
What you are looking for is a different behavior of the combobox:
Allow display of a default value
Once an element is selected, the text inside it is not underlined
A first approach could be based on the ComboBox template: the combobox is constructed in such a way that, if it is editable, its template
contains a textbox called PART_EditableTextBox
by acting on the textbox, for example by making it disabled, you can get the result you want.
And this can be implemented in different ways:
Inserting a code-behind event handler that disables the textbox when the combobox is loaded
With an Attached behavior that allows you to add custom behaviors to the controls (https://www.codeproject.com/Articles/28959/Introduction-to-Attached-Behaviors-in-WPF)
Write a custom control that maybe insert a watermark type part to your combobox
Now consider the first approach that is the fastest to implement so the code could be the following:
<ComboBox Name="LangComboBox" IsEditable="True" IsReadOnly="True"
Loaded="LangComboBox_Loaded"
Text="Select language">
<ComboBoxItem Content="English"/>
<ComboBoxItem Content="Spanish"/>
<ComboBoxItem Content="Both"/>
</ComboBox>
In the code-behind:
private void LangComboBox_Loaded(object sender, RoutedEventArgs e)
{
ComboBox ctrl = (ComboBox)sender;
TextBox Editable_tb = (TextBox)ctrl.Template.FindName("PART_EditableTextBox", ctrl);
if (Editable_tb != null)
{
// Disable the textbox
Editable_tb.IsEnabled = false;
}
}
This approach, however, has drawbacks, among which the fact that if the user wants to deselect / reset the value of the combo can not do it.
So you could follow another path using the MVVM pattern.
Coming from the world of web programming you should know the MVC pattern, in WPF the most common pattern is MVVM or Model - View - ViewModel
between the two patterns there are different things in common and I invite you to take a look at them: Mvvm Pattern.
You could create a class with the model that will be hosted in the combo for example:
public class Language
{
public int Id { get; set; }
public string Description { get; set; }
public Language(int id, string desc)
{
this.Id = id;
this.Description = desc;
}
}
public class YourDataContext : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private List<Language> _Languages;
public List<Language> Languages
{
get
{
return _Languages;
}
set
{
_Languages = value;
OnPropertyChanged("Languages");
}
}
private Language _selectedLanguage;
public Language SelectedLanguage
{
get
{
return _selectedLanguage;
}
set
{
_selectedLanguage = value;
OnPropertyChanged("SelectedLanguage");
}
}
public YourDataContext()
{
// Initialization of languages
Languages = new List<Language>();
Languages.Add(new Language(0, "None - Select a Language"));
Languages.Add(new Language(1, "English"));
Languages.Add(new Language(2, "Spanish"));
Languages.Add(new Language(3, "Both"));
SelectedLanguage = Languages.First();
}
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
// some other properties and commands
}
// Your Window class
public MainWindow()
{
InitializeComponent();
var dc = new YourDataContext();
DataContext = dc;
}
<ComboBox ItemsSource="{Binding Languages}"
DisplayMemberPath="Description"
SelectedItem="{Binding SelectedLanguage}"/>
Note that now the combobox is no longer editable and it is possible to reset the selection.
You can manage the selection using the model:
if(dc.SelectedLanguage.Id == 0)
{
//No language selected
}
There are a lot of different ways to achieve what you want, i hope this gave you some good point to start from.
Good programming to everyone.
I need to set the font family for the next text to be written in a RichTextBox.
I tried setting that with...
<RichTextBox x:Name="RichTextEditor" MaxWidth="1000" SpellCheck.IsEnabled="True"
FontFamily="{Binding ElementName=TextFontComboBox, Path=SelectedItem}"
FontSize="{Binding ElementName=TextSizeComboBox, Path=SelectedValue}"
Width="Auto" Height="Auto" HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Auto" />
...but it changed the whole text. I suppose that with the Selection property I can restrict the change to be applied just to the selected area. But how for the next -not yet typed- text?
In order to set the FontFamily based on the cursor position you need to define a custom control with a dependency property that helps insert a new Run section by overriding the OnTextInput method.
I included most of the code, you'll need to modify the namespaces to fit your development environment.
The code uses a ViewModel to manage the available fonts and manage if the font changed.
This code is only a prototype and does not deal with focusing issues between the two controls.
To use this code:
1- Type some text in the RichTectBox.
2- Change the font in the ComboBox.
3- Tab back to the RichTextBox.
4- Type some more text.
Here is the custom RichTextBox control:
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
namespace RichTextboxFont.Views
{
public class RichTextBoxCustom : RichTextBox
{
public static readonly DependencyProperty CurrentFontFamilyProperty =
DependencyProperty.Register("CurrentFontFamily",
typeof(FontFamily), typeof
(RichTextBoxCustom),
new FrameworkPropertyMetadata(new FontFamily("Tahoma"),
FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
new PropertyChangedCallback(OnCurrentFontChanged)));
public FontFamily CurrentFontFamily
{
get
{
return (FontFamily)GetValue(CurrentFontFamilyProperty);
}
set
{
SetValue(CurrentFontFamilyProperty, value);
}
}
private static void OnCurrentFontChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{}
protected override void OnTextInput(TextCompositionEventArgs e)
{
ViewModels.MainViewModel mwvm = this.DataContext as ViewModels.MainViewModel;
if ((mwvm != null) && (mwvm.FontChanged))
{
TextPointer textPointer = this.CaretPosition.GetInsertionPosition(LogicalDirection.Forward);
Run run = new Run(e.Text, textPointer);
run.FontFamily = this.CurrentFontFamily;
this.CaretPosition = run.ElementEnd;
mwvm.FontChanged = false;
}
else
{
base.OnTextInput(e);
}
}
}
}
Here is the XAML:
<Window x:Class="RichTextboxFont.Views.MainView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:RichTextboxFont.Views"
xmlns:ViewModels="clr-namespace:RichTextboxFont.ViewModels"
Title="Main Window"
Height="400" Width="800">
<DockPanel>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition/>
</Grid.RowDefinitions>
<ComboBox ItemsSource="{Binding Path=Fonts}"
SelectedItem="{Binding Path=SelectedFont, Mode=TwoWay}"/>
<local:RichTextBoxCustom Grid.Row="1"
CurrentFontFamily="{Binding Path=SelectedFont, Mode=TwoWay}"
FontSize="30"/>
</Grid>
</DockPanel>
</Window>
Here is the ViewModel:
If you do not use view models, let me know and I'll add the base class code too; otherwise, google/stackoverflow can help you too.
using System.Collections.ObjectModel;
using System.Windows.Media;
namespace RichTextboxFont.ViewModels
{
public class MainViewModel : ViewModelBase
{
#region Constructor
public MainViewModel()
{
FontFamily f1 = new FontFamily("Georgia");
_fonts.Add(f1);
FontFamily f2 = new FontFamily("Tahoma");
_fonts.Add(f2);
}
private ObservableCollection<FontFamily> _fonts = new ObservableCollection<FontFamily>();
public ObservableCollection<FontFamily> Fonts
{
get
{
return _fonts;
}
set
{
_fonts = value;
OnPropertyChanged("Fonts");
}
}
private FontFamily _selectedFont = new FontFamily("Tahoma");
public FontFamily SelectedFont
{
get
{
return _selectedFont;
}
set
{
_selectedFont = value;
FontChanged = true;
OnPropertyChanged("SelectedFont");
}
}
private bool _fontChanged = false;
public bool FontChanged
{
get
{
return _fontChanged;
}
set
{
_fontChanged = value;
OnPropertyChanged("FontChanged");
}
}
#endregion
}
}
Here is the Window code-behind where I initialise the ViewModel:
using System.Windows;
namespace RichTextboxFont.Views
{
public partial class MainView : Window
{
public MainView()
{
InitializeComponent();
this.DataContext = new ViewModels.MainViewModel();
}
}
}
There's a much easier way to do this: Implement a toolbar for your RichTextBox.
Unlike WinForms, the RichTextBox in WPF doesn't come with a toolbar by default, but it's really easy to create one yourself. The RichTextBox automatically handles many EditingCommands, so it's just a matter of creating a toolbar and some buttons. Microsoft has provided sample code for this at the bottom of the RichTextBox Overview on MSDN.
Unfortunately, those editing commands don't include setting the FontFace property of the selection, though you can create a ComboBox on the toolbar that can trigger the change with an event handler in the codebehind file.
That's the approach taken in this CodePlex article by Gregor Pross: WPF RichTextEditor
The project is commented in German, but the source itself is very clearly written. The codebehind used for his font selector ComboBox looks like this:
private void Fonttype_DropDownClosed(object sender, EventArgs e)
{
string fontName = (string)Fonttype.SelectedItem;
if (fontName != null)
{
RichTextControl.Selection.ApplyPropertyValue(System.Windows.Controls.RichTextBox.FontFamilyProperty, fontName);
RichTextControl.Focus();
}
}
The main reason that people struggle with the FontFace selection is that after the font selection has been made, you must return focus to the RichTextBox. If the user must manually press tab or click into the RichTextBox, a new text selection gets created and you lose the formatting options you've chosen.
One of the answers to this StackOverflow question discusses that problem.
WPF Richtextbox FontFace/FontSize
This isn't exactly a trivial answer.
To do inline text formatting in a Rich TextBox like you want you will have to modify the Document property of the RichTextBox. Very simply, something like this will work
<RichTextBox >
<RichTextBox.Document>
<FlowDocument>
<Paragraph>
<Run>Something</Run>
<Run FontWeight="Bold">Something Else</Run>
</Paragraph>
</FlowDocument>
</RichTextBox.Document>
</RichTextBox>
I think you could create a custom Control that creates a new block element and sets the font properties you need based on the user input.
For example, If the user types something then presses bold. You would want to wrap the previous text in a run and create a new run element setting the FontWeight to bold then the subsequent text will be wrapped in the bolded run.
Again, not a trivial solution but I can't think of any other way to accomplish what you are after.
I'm creating a standard menu in my WPF application.
I know that I can create custom commands, but I know there are also a bunch of standard commands to bind to.
For example, to open a file I should bind to ApplicationCommands.Open, to close a file I should bind to ApplicationCommands.Close. There's also a large number of EditCommands, ComponentCommands or NavigationCommands.
There doesn't seem to be an "Exit" command. I would have expected there to be ApplicationCommands.Exit.
What should I bind to the "Exit" menu item? To create a custom command for something this generic just seems wrong.
Unfortunately, there is no predefined ApplicationCommands.Exit. Adding one to WPF was suggested on Microsoft Connect in 2008: http://connect.microsoft.com/VisualStudio/feedback/details/354300/add-predefined-wpf-command-applicationcommands-exit. The item has been marked closed/postponed, however.
Mike Taulty discussed how to create your own Exit command in an article on his blog.
AFAIK there's no ApplicationCommands.Quit or ApplicationCommands.Exit, so I guess you're gonna have to create it yourself...
Anyway, if you're using the MVVM pattern, RoutedCommands are not exactly handy, so it's better to use a lightweight alternative like RelayCommand or DelegateCommand.
Not that complex actually (but still, M$ sucks for not providing it). Here you go:
public static class MyCommands
{
private static readonly ICommand appCloseCmd = new ApplicationCloseCommand();
public static ICommand ApplicationCloseCommand
{
get { return appCloseCmd; }
}
}
//===================================================================================================
public class ApplicationCloseCommand : ICommand
{
public event EventHandler CanExecuteChanged
{
// You may not need a body here at all...
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public bool CanExecute(object parameter)
{
return Application.Current != null && Application.Current.MainWindow != null;
}
public void Execute(object parameter)
{
Application.Current.MainWindow.Close();
}
}
And the body of the AplicationCloseCommand.CanExecuteChanged event handler may not be even needed.
You use it like so:
<MenuItem Header="{DynamicResource MenuFileExit}" Command="MyNamespace:MyCommands.ApplicationCloseCommand"/>
Cheers!
(You cannot imagine how long it took me to discover this Command stuff myself...)
Yes, it would've made a lot of sense for Microsoft to include an ApplicationCommands.Exit command in their collection of pre-defined commands. It disappoints me that they didn't. But as the answers to this question demonstrate, not all is lost.
There are lots of workarounds possible for the lack of a proper ApplicationCommands.Exit object. However, I feel most miss the point. Either they implement something in the view model, for something that really is strictly a view behavior (in some cases reaching into the view object graph with e.g. Application.Current.MainWindow!), or they write a bunch of code-behind to do what XAML does very well and much more conveniently.
IMHO, the simplest approach is just to declare a RoutedUICommand resource for the window, attach that to a command binding, and to a menu item, to hook all the parts up. For example:
<Window x:Class="ConwaysGameOfLife.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Window.Resources>
<RoutedUICommand x:Key="fileExitCommand" Text="File E_xit">
<RoutedUICommand.InputGestures>
<KeyGesture >Alt+F4</KeyGesture>
</RoutedUICommand.InputGestures>
</RoutedUICommand>
</Window.Resources>
<Window.CommandBindings>
<CommandBinding Command="{StaticResource fileExitCommand}" Executed="fileExitCommand_Executed"/>
</Window.CommandBindings>
<DockPanel>
<Menu DockPanel.Dock="Top">
<MenuItem Header="_File">
<!-- other menu items go here -->
<Separator/>
<MenuItem Command="{StaticResource fileExitCommand}"/>
</MenuItem>
</Menu>
<!-- the main client area UI goes here -->
</DockPanel>
</Window>
The Executed event handler for the command binding is trivial:
private void fileExitCommand_Executed(object sender, ExecutedRoutedEventArgs e)
{
Close();
}
Assuming, of course, your program implementation follows the usual semantics of closing the main window to exit the program.
In this way, all of the UI-specific elements go right into the RoutedUICommand object, which can be configured correctly and conveniently right in the XAML rather than having to declare a new C# class to implement the command and/or mess around with the input bindings from code-behind. The MenuItem object already knows what to do with a RoutedUICommand in terms of display, so going this route provides a nice decoupling of the command's properties from the rest of the UI. It also provides a convenient way to provide a secondary key gesture, in case you'd prefer something other than the default Alt+F4 (e.g. Ctrl+W).
You can even put the RoutedUICommand declaration in the App.xaml file, for reuse among multiple windows in your program, should they exist. Again, decoupling the UI-specific aspects, which are declared in the resource, from the consumers that are found throughout the program.
I find this approach much more generalizable and easily implemented than the other options which I've seen presented (here and elsewhere).
private void MenuItem_Click(object sender, RoutedEventArgs e)
{
Application.Current.Shutdown();
}
Pretty simple to do:
using System.Windows.Input;
namespace YourApp
{
static class ApplicationCommands
{
public static RoutedCommand Quit { get; }
static ApplicationCommands()
{
var inputGestures = new InputGestureCollection();
inputGestures.Add(new KeyGesture(Key.Q, ModifierKeys.Control));
Quit = new RoutedUICommand("Quit", "Quit", typeof(ApplicationCommands),
inputGestures);
}
}
}
Use it in your XAML like this:
<Window.CommandBindings>
<CommandBinding Command="local:ApplicationCommands.Quit"
Executed="QuitCommandOnExecuted"/>
</Window.CommandBindings>
[..]
<MenuItem Command="local:ApplicationCommands.Quit" />
Code-behind:
void QuitCommandOnExecuted(object sender, ExecutedRoutedEventArgs e)
{
Application.Current.Shutdown();
}
You can modify the Text property of a command before you bind it in a window. This will change the text of the command everywhere it appears in your ui.
EDIT: Do this to Close in the Window or App ctor
Suppose I have a view implemented as a DataTempate inside a resource Dictionary.
And I have a corresponding ViewModel.
Binding Commands are easy. But what if my View contains a control such as a ListBox, and I need to Publish an application wide event (Using Prism's Event Aggreagtor) based on the Item being Changed on the List.
if ListBox supports a command I could just bind it to a command in the ViewModel and publish the event. But Listbox doesn't allow such an option.
How do I bridge this?
EDIT:
Many great answers.
Take a look at this link http://blogs.microsoft.co.il/blogs/tomershamam/archive/2009/04/14/wpf-commands-everywhere.aspx
Thanks
Ariel
Instead of trying to bind a command to when the item changes, I looked at the problem another way.
If you bind the selected item of the ListBox to a property in the ViewModel, then when that property is changed you can publish the event. That way the ViewModel remains the source of the event and it is triggered by the item changing, which is what you want.
<ListBox ItemsSource="{Binding Items}" SelectedItem="{Binding SelectedItem}" />
...
public class ViewModel
{
public IEnumerable<Item> Items { get; set; }
private Item selectedItem;
public Item SelectedItem
{
get { return selectedItem; }
set
{
if (selectedItem == value)
return;
selectedItem = value;
// Publish event when the selected item changes
}
}
Extend the control to support ICommandSource and decide which action should trigger the command.
I did this with Combo Box and used OnSelectionChanged as the trigger for the command. First I will show in XAML how I bind the command to the extended Control ComboBox which I called CommandComboBox, then I will show the code for CommandComboBox that adds the support for the ICommandSource to ComboBox.
1) Using CommandComboBox in your XAML code:
In your XAML namespace declarations include
xmlns:custom="clr-namespace:WpfCommandControlsLibrary;assembly=WpfCommandControlsLibrary">
Use the CommandComboBox in place of ComboBox and bind the command to it like so: Note that in this example I have a defined a command called SetLanguageCommand im my ViewModel and I am passing the selected value for this ComboBox as the parameter to the command.
<custom:CommandComboBox
x:Name="ux_cbSelectLanguage"
ItemsSource="{Binding Path = ImagesAndCultures}"
ItemTemplate="{DynamicResource LanguageComboBoxTemplate}"
Command="{Binding Path=SetLanguageCommand, Mode=Default}"
CommandParameter="{Binding RelativeSource={x:Static RelativeSource.Self}, Path=SelectedValue, Mode=Default}"
IsSynchronizedWithCurrentItem="True"
HorizontalAlignment="Right"
VerticalAlignment="Center"
Grid.Column="1" Margin="0,0,20,0" Style="{DynamicResource GlassyComboBox}" ScrollViewer.IsDeferredScrollingEnabled="True"
/>
2) The code for CommandComboBox
The code for the file CommandComboBox.cs is included below. I added this file to a Class Library called WpfCommandControlsLibrary and made it a separate project so I could easily add any extend commands to whatever solution needed to use them and so I could easily add additional WPF Controls and extend them to support the ICommandSource inteface.
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
namespace WpfCommandControlsLibrary
{
/// <summary>
/// Follow steps 1a or 1b and then 2 to use this custom control in a XAML file.
///
/// Step 1a) Using this custom control in a XAML file that exists in the current project.
/// Add this XmlNamespace attribute to the root element of the markup file where it is
/// to be used:
///
/// xmlns:MyNamespace="clr-namespace:WpfCommandControlsLibrary"
///
///
/// Step 1b) Using this custom control in a XAML file that exists in a different project.
/// Add this XmlNamespace attribute to the root element of the markup file where it is
/// to be used:
///
/// xmlns:MyNamespace="clr-namespace:WpfCommandControlsLibrary;assembly=WpfCommandControlsLibrary"
///
/// You will also need to add a project reference from the project where the XAML file lives
/// to this project and Rebuild to avoid compilation errors:
///
/// Right click on the target project in the Solution Explorer and
/// "Add Reference"->"Projects"->[Select this project]
///
///
/// Step 2)
/// Go ahead and use your control in the XAML file.
///
/// <MyNamespace:CustomControl1/>
///
/// </summary>
public class CommandComboBox : ComboBox, ICommandSource
{
public CommandComboBox() : base()
{
}
#region Dependency Properties
// Make Command a dependency property so it can use databinding.
public static readonly DependencyProperty CommandProperty =
DependencyProperty.Register(
"Command",
typeof(ICommand),
typeof(CommandComboBox),
new PropertyMetadata((ICommand)null,
new PropertyChangedCallback(CommandChanged)));
public ICommand Command
{
get
{
return (ICommand)GetValue(CommandProperty);
}
set
{
SetValue(CommandProperty, value);
}
}
// Make CommandTarget a dependency property so it can use databinding.
public static readonly DependencyProperty CommandTargetProperty =
DependencyProperty.Register(
"CommandTarget",
typeof(IInputElement),
typeof(CommandComboBox),
new PropertyMetadata((IInputElement)null));
public IInputElement CommandTarget
{
get
{
return (IInputElement)GetValue(CommandTargetProperty);
}
set
{
SetValue(CommandTargetProperty, value);
}
}
// Make CommandParameter a dependency property so it can use databinding.
public static readonly DependencyProperty CommandParameterProperty =
DependencyProperty.Register(
"CommandParameter",
typeof(object),
typeof(CommandComboBox),
new PropertyMetadata((object)null));
public object CommandParameter
{
get
{
return (object)GetValue(CommandParameterProperty);
}
set
{
SetValue(CommandParameterProperty, value);
}
}
#endregion
// Command dependency property change callback.
private static void CommandChanged(DependencyObject d,
DependencyPropertyChangedEventArgs e)
{
CommandComboBox cb = (CommandComboBox)d;
cb.HookUpCommand((ICommand)e.OldValue, (ICommand)e.NewValue);
}
// Add a new command to the Command Property.
private void HookUpCommand(ICommand oldCommand, ICommand newCommand)
{
// If oldCommand is not null, then we need to remove the handlers.
if (oldCommand != null)
{
RemoveCommand(oldCommand, newCommand);
}
AddCommand(oldCommand, newCommand);
}
// Remove an old command from the Command Property.
private void RemoveCommand(ICommand oldCommand, ICommand newCommand)
{
EventHandler handler = CanExecuteChanged;
oldCommand.CanExecuteChanged -= handler;
}
// Add the command.
private void AddCommand(ICommand oldCommand, ICommand newCommand)
{
EventHandler handler = new EventHandler(CanExecuteChanged);
canExecuteChangedHandler = handler;
if (newCommand != null)
{
newCommand.CanExecuteChanged += canExecuteChangedHandler;
}
}
private void CanExecuteChanged(object sender, EventArgs e)
{
if (this.Command != null)
{
RoutedCommand command = this.Command as RoutedCommand;
// If a RoutedCommand.
if (command != null)
{
if (command.CanExecute(CommandParameter, CommandTarget))
{
this.IsEnabled = true;
}
else
{
this.IsEnabled = false;
}
}
// If a not RoutedCommand.
else
{
if (Command.CanExecute(CommandParameter))
{
this.IsEnabled = true;
}
else
{
this.IsEnabled = false;
}
}
}
}
// If Command is defined, selecting a combo box item will invoke the command;
// Otherwise, combo box will behave normally.
protected override void OnSelectionChanged(SelectionChangedEventArgs e)
{
base.OnSelectionChanged(e);
if (this.Command != null)
{
RoutedCommand command = Command as RoutedCommand;
if (command != null)
{
command.Execute(CommandParameter, CommandTarget);
}
else
{
((ICommand)Command).Execute(CommandParameter);
}
}
}
// Keep a copy of the handler so it doesn't get garbage collected.
private static EventHandler canExecuteChangedHandler;
}
}
One option is to extend the control in question and add support for the particular command you require. For example, I've modified ListView before to support the ItemActivated event and related command.
Well, nobody answered.
So I've gave up and moved the implementation of the View outside the Dictionary into a regular UserControl, I've injected him a reference to the ViewModel.
Now when the ListBox fire the Event it's calls the ViewModel and from there everything is possible again.
Ariel
A great solution to this type of problem comes from the usage of Attached Properties.
Marlon Grech has taken the usage of Attached Properties to the next level by creating Attached Command Behaviors. Using these it is possible to bind any Command existing in a ViewModel to any Event existing in the view.
This is something I use a lot to deal with similar issues with ListBoxes, where I want them to open, or edit or do some action on a double click.
In this example I'm using an older version of Attached Command Behaviors, but the effect is the same. I have a style that is used for ListBoxItems which I am explicitly keying to.
However, it would be easy enough to create a application or window wide style applying to all ListBoxItems that sets the commands at a much higher level. Then, whenever the event for the ListBoxItem attached to the CommandBehavior.Event property would fire, it instead fires off the attached Command.
<!-- acb is the namespace reference to the Attached Command Behaviors -->
<Style x:Key="Local_OpenListItemCommandStyle">
<Setter Property="acb:CommandBehavior.Event"
Value="MouseDoubleClick" />
<Setter Property="acb:CommandBehavior.Command"
Value="{Binding ElementName=uiMyListBorder, Path=DataContext.OpenListItemCommand}" />
<Setter Property="acb:CommandBehavior.CommandParameter"
Value="{Binding}" />
</Style>
<DataTemplate x:Key="MyView">
<Border x:Name="uiMyListBorder">
<ListBox ItemsSource="{Binding MyItems}"
ItemContainerStyle="{StaticResource local_OpenListItemCommandStyle}" />
</Border>
</DataTemplate>
I have been writing behaviors (attached properties) to do this, and there are still cases where I need them.
For the usual case however, simply binding an event to a command, you can do everything in Xaml if you have Blend SDK 4 installed. Note that you will have to add a reference to System.Windows.Interactivity.dll, and to redistribute this assembly.
Expression Blend SDK for .NET 4
Microsoft SDKs (for future reference)
This example is invoking an ICommand DragEnterCommand on the ViewModel when the DragEnter event of the Grid is fired:
<UserControl xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity" >
<Grid>
<i:Interaction.Triggers>
<i:EventTrigger EventName="DragEnter">
<i:InvokeCommandAction Command="{Binding DragEnterCommand}" CommandParameter="{Binding ...}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</Grid>
</UserControl>
Try using Prism 2.
It comes with great extensions to commanding and opens many new posibilites (like commands to being tied to visual tree).
The following RoutedCommand example works.
However, the handling for the button which executes the command is in the codebehind of the view. The way I understand MVVM, it should be in the ViewModel.
However, When I move the method to the ViewModel (and change it to public), I get the error "ManagedCustomersView does not contain a definition of OnSave". Even if I change the RoutedCommand second parameter to typeof(ManageCustomersViewModel), I get the same error.
How can I move the command handler from the View-codebehind to the ViewModel?
ManageCustomersView.xaml:
<UserControl.CommandBindings>
<CommandBinding Command="local:Commands.SaveCustomer" Executed="OnSave"/>
</UserControl.CommandBindings>
...
<Button Style="{StaticResource formButton}"
Content="Save"
Command="local:Commands.SaveCustomer"
CommandParameter="{Binding Id}"/>
ManageCustomersView.xaml.cs:
private void OnSave(object sender
, System.Windows.Input.ExecutedRoutedEventArgs e)
{
int customerId = ((int)e.Parameter);
MessageBox.Show(String.Format
("You clicked the save button for customer with id {0}.", customerId));
}
Commands.cs:
using System.Windows.Input;
using TestDynamicForm123.View;
namespace TestDynamicForm123
{
public class Commands
{
public static RoutedCommand SaveCustomer =
new RoutedCommand("SaveCustomer", typeof(ManageCustomersView));
}
}
You'll expose a property off your ViewModel that references the command.
class MyViewModel
{
public RoutedCommand SaveCmd{ get{ return Commands.SaveCustomer; } }
}
Then in the XAML
<Button Command="{Binding SaveCmd}" />
However you might find it easier to use the RelayCommand so that you can define the actual command logic in your model as well.