I am new to wpf application and I am working on application and i have created a menu Now i want to function menu items event on short key ctrl+o, ctrl+n etc. How can i do it.please give me in details.
You can so it in the following way....
In Xaml file
<Window x:Class="FocusDemo.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:FocusDemo"
Title="Window1" Height="300" Width="300">
<Window.CommandBindings>
<CommandBinding
Command=
"{x:Static
local:Window1.CustomRoutedCommand}"
Executed="ExecutedCustomCommand"
CanExecute="CanExecuteCustomCommand" >
</CommandBinding>
</Window.CommandBindings>
<Window.InputBindings>
<KeyBinding
Command=
"{x:Static
local:Window1.CustomRoutedCommand}"
Key="S"
Modifiers="Control"/>
</Window.InputBindings>
<Grid>
<!--Your Controls-->
</Grid>
</Window>
In the Code behind file
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
public static RoutedCommand CustomRoutedCommand = new RoutedCommand();
public Window1()
{
InitializeComponent();
}
#region
public void ExecutedCustomCommand(object sender, ExecutedRoutedEventArgs e)
{
MessageBox.Show("Ctrl+S");
}
public void CanExecuteCustomCommand(object sender,
CanExecuteRoutedEventArgs e)
{
e.CanExecute = true;
}
#endregion
}
Source : Click here
Please dont forget to mark the answer if its correct
I know it is not exact answer to the question, but probably anybody like me was searching for the way to put ANY keyboard shortcuts to menu items (command buttons) like Alt+O, Alt+N. In this case, you can just put undescore character (_) before the shortcut character in the item name.
Related
I'm trying to execute a method when the user presses ctrl + Tab. If there is more than one window (App.Current.Windows >1), then CanExecute should be true, otherwise false.
All posts I read so far suggest I need to write a subclass for ICommand and a ViewModel which is basically the "link" between the UI and tge custom command. I've read some examples
of how to create bindings
and because I didn't get this I tried to
learn more about MVVM
but I'm afraid I'm still feeling clueless.
What would an example checking for more than one window open and executing a method SomeMethod if CanExecute was true look like? Where would I place what? I'm sorry, but I searched and tried all day - and still feel clueless.
Any examples or pointers to good explanations?
Here is how you can do it
in Xaml:
<Window x:Class="Test.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="ExecuteCommand" Text="ExecuteCommand" />
</Window.Resources>
<Window.InputBindings>
<KeyBinding Key="Tab" Modifiers="Ctrl" Command="{StaticResource ExecuteCommand}" />
</Window.InputBindings>
<Window.CommandBindings>
<CommandBinding Command="{StaticResource ExecuteCommand}" CanExecute="ExecuteCommand_CanExecute" Executed="ExecuteCommand_Executed" />
</Window.CommandBindings>
<Grid>
</Grid>
</Window>
In Code Behind:
private void ExecuteCommand_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = App.Current.Windows.Count > 1;
}
private void ExecuteCommand_Executed(object sender, ExecutedRoutedEventArgs e)
{
MessageBox.Show("Hello");
}
Hope it helps.
I am getting the feeling that you are new to WPF and MVVM, Although it's recommended, you don't have to use MVVM with WPF. You can do the same thing by event handlers.
Here is something you might want to try:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
KeyUp += MainWindow_KeyUp;
}
private void MainWindow_KeyUp(object sender, KeyEventArgs e)
{
if (e.Key == Key.Tab && (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl)))
{
MessageBox.Show(App.Current.Windows.Count.ToString());
}
}
}
I've dumbed down the code as much as I could to try and get a working piece of code yet I'm still coming up short. Some advice would be appreciated.
I'm trying to get a DependencyProperty working, it's that simple and yet the data I'm setting on the main window isn't showing up in the user control.
In the MainWindow I'm setting the TextValue to "hi" in the xaml. TextValue is showing in the xaml up and compiling just fine so I'm pretty sure I have the DependencyProperty set right. Once the dialog is fully open I take a look in the debugger and my property TextValue is still null.
Am I missing setting the data context? Maybe I'm off base in what I'm looking to do.
Thanks for taking the time to figure out what I'm doing wrong.
My User Control is: UserControl1
Xaml:
<UserControl x:Class="WpfApplication1.UserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
Loaded="UserControl_Loaded"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid>
</Grid>
</UserControl>
UserControl1.xaml.cs is:
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for UserControl1.xaml
/// </summary>
public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
}
public static readonly DependencyProperty TextProperty = DependencyProperty.Register("TextValue", typeof(string), typeof(UserControl1));
private string _tv;
public string TextValue
{
get
{
return _tv;
}
set
{
_tv = value;
}
}
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
}
}
}
My calling window xaml is:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:usercontrols="clr-namespace:WpfApplication1"
Title="MainWindow" Height="350" Width="525"
Loaded='Window_Loaded'>
<Grid>
<usercontrols:UserControl1 x:Name="usercontroltest1" TextValue="hi"/>
</Grid>
</Window>
My calling window .cs is:
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
}
}
}
The getter and setter of the "property wrapper" must call the GetValue and SetValue methods of the DependencyObject base class like shown below. Besides that, there is a naming convention that mandates that a dependency property's identifier field is named like the property plus a Property suffix. See Custom Dependency Properties for all the details.
public static readonly DependencyProperty TextValueProperty =
DependencyProperty.Register(
nameof(TextValue), typeof(string), typeof(UserControl1));
public string TextValue
{
get { return (string)GetValue(TextValueProperty); }
set { SetValue(TextValueProperty, value); }
}
In order to access a UserControl's dependency property in its own XAML, you would typically use a RelativeSource Binding like this:
<UserControl x:Class="WpfApplication1.UserControl1" ...>
<Grid>
<TextBlock Text="{Binding TextValue,
RelativeSource={RelativeSource AncstorType=UserControl}}" />
</Grid>
</UserControl>
I'm trying to get my head around RoutedCommands in WPF. I like how they decrease coupling between different UI elements and the models but I can't seem to make the bindings work for custom controls that are children to the window. I guess this will be some easy creds for any of you WPF wizards out there! :-)
Here's some example code that can be tried out:
The routed command:
using System.Windows.Input;
namespace Wpf.RoutedCommands
{
public static class Commands
{
public static readonly RoutedCommand SayHi = new RoutedCommand();
}
}
Main window XAML:
<Window x:Class="Wpf.RoutedCommands.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"
xmlns:local="clr-namespace:Wpf.RoutedCommands"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<!-- uncommenting the below makes it work but introduces coupling -->
<!--<Window.CommandBindings>
<CommandBinding Command="{x:Static local:Commands.SayHi}" Executed="cmdSayHi" CanExecute="cmdCanSayHi"></CommandBinding>
</Window.CommandBindings>-->
<DockPanel LastChildFill="True">
<Button DockPanel.Dock="Bottom" Content="Say Hi!" Command="{x:Static local:Commands.SayHi}" />
<local:Greeter x:Name="Greeter" />
</DockPanel>
Main window code:
using System.Windows.Input;
namespace Wpf.RoutedCommands
{
public partial class MainWindow
{
public MainWindow()
{
InitializeComponent();
}
// these two will be used if you uncomment the command bindings in XAML
private void cmdCanSayHi(object sender, CanExecuteRoutedEventArgs e) => e.CanExecute = true;
private void cmdSayHi(object sender, ExecutedRoutedEventArgs e) => Greeter.SayHi();
}
}
Custom control ("Greeter") XAML:
<UserControl x:Class="Wpf.RoutedCommands.Greeter"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:Wpf.RoutedCommands"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<UserControl.CommandBindings>
<CommandBinding Command="{x:Static local:Commands.SayHi}" Executed="cmdSayHi" CanExecute="cmdCanSayHi"/>
</UserControl.CommandBindings>
<Grid>
<Label x:Name="Label" />
</Grid>
Greeter code:
using System.Windows.Input;
namespace Wpf.RoutedCommands
{
public partial class Greeter
{
public Greeter()
{
InitializeComponent();
}
private void cmdSayHi(object sender, ExecutedRoutedEventArgs e) => SayHi();
private void cmdCanSayHi(object sender, CanExecuteRoutedEventArgs e) => e.CanExecute = true;
public void SayHi() => Label.Content = "Hi!";
}
}
If you create a WPF project and use the above you will see that the button in main window is disabled. Debugging it shows that the Greeter.cmdCanSayHi method never gets called.
If you uncomment the dormant XAML in main window everything works. So: Why can I bind to commands from the window but not from its child controls? Is it to do with rendering timing or something?
A RoutedCommand searches the visual tree from the focused element and up for an element that has a matching CommandBinding and then executes the Execute delegate for this particular CommandBinding.
Your UserControl is located below the Button in the element tree.
I have a WPF project with two windows, the first window firing events and have it's own event handlers, the other window will fire the same events, any idea how to use handlers in first window to handle events in second window ?
thanks to #Cody Gray , #keyboardP and to this useful article http://geekswithblogs.net/lbugnion/archive/2007/03/02/107747.aspx
Here's a code snippet to demonstrate the answer:
first step add a new subclass :
using System.Windows;
namespace WpfApplication
{
public class Subclass : Window
{
//Event handlers,functions or any potential reused code
}
}
Second step: go to window1.xaml.cs
namespace WpfApplication
{
public partial class Window1 : Subclass
{
public Window1()
{
InitializeComponent();
}
}
}
Third step: change the Xaml code for window1 as below:
<src:Subclass
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:src="clr-namespace:WpfApplication"
Title="Window1" Height="350" Width="525">
</src:Subclass>
Finally do 2nd & 3rd steps for window2
A simple sample of what i was proposing in first place:
<Window x:Class="Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Grid>
<Window Loaded="Window_Loaded"/>
<Window Loaded="Window_Loaded"/>
</Grid>
</Window>
Look how both windows share the event handler:
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
//Whatever
}
}
At this point you should ask yourself if you really needed two windows, or any other container control could be enough.
I have a WPF Combobox with a ListView + "X"-Button in the Popup-DropDown. I am showing search results in that listview.
How can I make the popup close ONLY when the user clicks my "X"-Button in the popup?
You will probably have to write a custom control template for a permanently open listbox, or change the default one to behave like this. Inside the control template you have to set the StaysOpen property of the Popup to true and make your button switch that value
Short example
<Window x:Class="WPFComboSample.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<ComboBox Name="Combo">
<TextBox></TextBox>
<Button Name="Close" Width="150" Height="200" Click="Close_Click">Close</Button>
</ComboBox>
</Grid>
namespace WPFComboSample
{
/// <summary>
/// Interaktionslogik für MainWindow.xaml>
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Close_Click(object sender, RoutedEventArgs e)
{
Combo.IsDropDownOpen = false;
}
}
}