Flexible Close Command - wpf

I am searching for a way how to realize a window close command, which is usable in the window's CommandBindings and by other sources, for example a button. I am working with MVVM. So far, I only found solutions that were either meant for use by CommandBindings or with a simple Command featured inside the MVVM. I need to have one central handler for this.
Thanks in advance!

Simply use EventToCommand.
ViewModel:
public ICommand WindowClosing
{
get
{
return new RelayCommand<CancelEventArgs>(
(args) =>{
});
}
}
and in XAML:
<i:Interaction.Triggers>
<i:EventTrigger EventName="Closing">
<command:EventToCommand Command="{Binding WindowClosing}" />
</i:EventTrigger>
</i:Interaction.Triggers>

Related

wpf xaml resource dictionary add custom property

I want to use the following xaml code for navigation in some pages:
<Button Content="Go to page2">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<ei:ChangePropertyAction PropertyName="Source" TargetObject="{Binding NavigationService, RelativeSource={RelativeSource AncestorType={x:Type Page}, Mode=FindAncestor}}">
<ei:ChangePropertyAction.Value>
<System:Uri>Page2.xaml</System:Uri>
</ei:ChangePropertyAction.Value>
</ei:ChangePropertyAction>
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
So I´m wondering if there is a possibility to outsource the interaction part into a style (in a resource dictionary) and add a custom property like "NavigationUri" where you can directly declare the page to navigate to.
Another idea (which would probably be the better approach) is to create a custom control and inherit from button class.
Anywhere I would prefer a more compact and lean way without code behind.
Please let me know, which is the more suitable solution and how to implement it.
Although there are various simple techniques to make our Behavior Xaml as static resource. But, we need a custom behavior, as we are using a parameter in the form of Page name to navigate to. This variable demands programming.
So, I came up with
a. Custom behavior(NavigationBehavior), and
b. Button subclassing(NavigationButton)
NavigationBehavior
using System;
using System.Windows.Controls;
using System.Windows.Interactivity;
namespace WpfApplication1.Navigation
{
public class NavigationBehavior:Behavior<NavigationButton>
{
protected override void OnAttached()
{
AssociatedObject.Click += AssociatedObject_Click;
base.OnAttached();
}
void AssociatedObject_Click(object sender, System.Windows.RoutedEventArgs e)
{
((Page)AssociatedObject.DataContext).NavigationService.Source = new Uri(AssociatedObject.DestinationUri, UriKind.Relative);
}
}
}
NavigationButton
namespace WpfApplication1.Navigation
{
public class NavigationButton : Button
{
NavigationBehavior behavior = new NavigationBehavior();
public NavigationButton()
{
behavior.Attach(this);
}
public string DestinationUri { get; set; }
}
}
Usage :
<nav:NavigationButton Content="Navigate to Page2" DestinationUri="/Navigation/Page2.xaml" />
Important Note
We are using DataContext property in our behavior to get access to the containing page. So, set this.DataContext = this; in the constructor of your all pages.
One can try using a common base class / interface to avoid this.
you cannot have interaction triggers extracted but there is a workaround to get this done
you can create a Button in resources with interaction logic in it, and then where needed you can have a content control with content set to your resource.
something like this --
<Window.Resources>
<Button x:Key="MyButton"
Content="Go to page2">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<ei:ChangePropertyAction PropertyName="Source" TargetObject="{Binding NavigationService, RelativeSource={RelativeSource AncestorType={x:Type Page}, Mode=FindAncestor}}">
<ei:ChangePropertyAction.Value>
<System:Uri>Page2.xaml</System:Uri>
</ei:ChangePropertyAction.Value>
</ei:ChangePropertyAction>
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
</Window.Resources>
<Grid>
<ContentControl Name="MyLocalButton" Content="{StaticResource MyButton}" />
</Grid>
You should put the navigation logic in a command in each page's view model and bind the buttons' Command properties to those commands, or else give the view models each a NextPage property and bind to that.
And create separate buttons in the views. Define a Style in the resource dictionary to make them all look the same.
Defining a Button as a resource is a bad idea. Among other things, there's only one instance of it and it can have only one visual parent, so when you add it to one view it'll vanish from the last. And you run into ugly problems like this one. You're working against XAML, and XAML is already hard enough when you're working with it.

Assign shortcut key in WPF Ribbon Button

I have a WPF Ribbon Button and I want it to have a shortcut key. (e.g. Ctrl+A). Been searching in google but lost to get a possible answer. Does anyone knows how I might deal with this? Thanks =)
Here is what I have so far
<my:RibbonButton Name="rb1" Content="Images/save.png" />
<my:RibbonButton Name="rb2" Content="Images/abort.png" />
you may perhaps use UIElement.InputBindings with KeyBinding
example
<Window.InputBindings>
<KeyBinding Key="S"
Modifiers="Control"
Command="{Binding Save}" />
<KeyBinding Key="A"
Modifiers="Control"
Command="{Binding Abort}" />
</Window.InputBindings>
using this approach you can bind the input gestures to the commands which buttons are using
assumed code
<my:RibbonButton Name="rb1" Content="Images/save.png" Command="{Binding Save}" />
<my:RibbonButton Name="rb2" Content="Images/abort.png" Command="{Binding Abort}" />
from MSDN: KeyBinding
A KeyBinding associates a KeyGesture with a ICommand, such as a RoutedCommand. RoutedCommand is the primary implementation of the ICommand interface for the WPF commanding system . In general, when the KeyGesture is executed the command is invoked, although the command behavior is further influenced by command-specific factors such as the CanExecute value.
I prefer doing it in code behind. I am using the code in my program.
Hope it help.
private void AddHotKeys()
{
try
{
RoutedCommand firstHotkey = new RoutedCommand();
firstHotkey .InputGestures.Add(new KeyGesture(Key.S, ModifierKeys.Alt));
CommandBindings.Add(new CommandBinding(firstHotkey , Save));
}
catch (Exception err)
{
//handle exception error
}
}

How to trigger ViewModel command for a specific button events

How can a command on a ViewModel be invoked by a specific event of a button, such as MouseDoubleClick?
You can use the EventTrigger in the System.Windows.Interactivity namespace, which is part of the so-called Prism framework. If you're just getting started with MVVM, don't care too much for Prism by now, but keep it in mind for later. Anyway, you can steel the EventTrigger
It works like this:
Reference the assembly System.Windows.Interactivity.dll
In XAML, reference the namespace:
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
Then in your Button or any other control, add a EventTrigger like this:
<Button Content="Button">
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseDoubleClick">
<i:InvokeCommandAction Command="{Binding CommandToBindTo}"
CommandParameter="{Binding CommandParameterToBindTo}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
This way, you bind your event to a Command on your DataContext.
Remark
To clarify the usage, here's a kind of real life example including the ViewModel. The fictional requirement is to allow the user to select an item in a list and then perform a command which takes the selected item as a parameter:
<ListBox x:Name="ItemsList" ItemsSource="{Binding Items}" />
<Button Content="Do something with selected item">
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseDoubleClick">
<i:InvokeCommandAction Command="{Binding DoSomethingCommand}"
CommandParameter="{Binding SelectedItem,
ElementName=ItemsList}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
And that would be the ViewModel. Note how the parameter to the command is used, in the example with a generic version of a DelegateCommand object as you get it in every MVVM framework (sometimes RelayCommand). This class takes the type of the required parameter as a generic parameter (here ItemViewModel) and requires a method which takes an according parameter (here ExecuteDoSomethingWithItem(ItemViewModel ...)). The rest is WPF magic: The oject to which the CommandParameter property is bound in your XAML will be passed through as the parameter in your Execute(...) function.
public class ViewModel
{
ObservableCollection<ItemViewModel> Items { get; set; }
public ICommand DoSomethingCommand
{
get
{
return _doSomethingCommand ??
(_doSomethingCommand = new DelegateCommand<ItemViewModel>(ExecuteDoSomethingWithItem));
}
}
private DelegateCommand<ItemViewModel> _doSomethingCommand;
private void ExecuteDoSomethingWithItem(ItemViewModel itemToDoSomethingWith)
{
// Do something
}
public ViewModel()
{
Items = new ObservableCollection<ItemViewModel>();
// Fill the collection
}
}
Have fun with learning MVVM, it's worth it.
you can use attached command behaviors
=> http://geekswithblogs.net/HouseOfBilz/archive/2009/08/21/adventures-in-mvvm-ndash-generalized-command-behavior-attachments.aspx
You need to do a lot of pluming yourself if you going to use Command and Event Binding from out of the box WPF. You can gain a lot of just using existing framework such as MVVM Light Toolkit, or Cliburn Micro that already provide command and even binding.

Issues with EventToCommand for the Loaded event

So I am using GalaSoft's EventToCommand for binding my View's Loaded event to my command in my ViewModel. The binding is working great but my Command is never being executed. The only way I have been able to get this to work is to handle the Loaded event in my View's code behind and then cast my DataContent to my VM and tell it to run my code (which the command is trying to do). Obviously this isnt very nice when trying to do it all MVVM like. FYI I did try the MouseEnter event and that worked great so that makes me think its a timing issue. Also, my View is a user control.
View:
<i:Interaction.Triggers>
<i:EventTrigger EventName="Loaded">
<cmd:EventToCommand PassEventArgsToCommand="False" Command="{Binding Path=DownloadDataCommand}" />
</i:EventTrigger>
</i:Interaction.Triggers>
ViewModel:
public RelayCommand DownloadDataCommand
{
get { return new RelayCommand(() => DownloadDataAsync()); }
}
Ive tried calling simple methods that do pretty much nothing and my relay command is still not invoked. So I doubt its the action within the RelayCommand. Does anyone see what I am doing wrong?

Silverlight 4 EventTrigger Handled

I have two nested Grid (FrameworkElement) items in my application.
<UserControl xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity">
<Grid x:name="OuterGrid">
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseLeftButtonDown">
<i:InvokeCommandAction x:Name="TheOuterCommand" Command="{Binding OuterCommand}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
<Grid x:name="InnerGrid">
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseLeftButtonDown">
<i:InvokeCommandAction x:Name="TheInnerCommand" Command="{Binding InnerCommand}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</Grid>
</Grid>
</UserControl>
Each of the InvokeCommands is attached to a DelegateCommand (from the Prism libraries) in the viewmodel.
OuterCommand = new DelegateCommand(OuterCommandMethod, e => true);
InnerCommand = new DelegateCommand(InnerCommandMethod, e => true);
At the moment, the EventTrigger on InnerGrid also triggers the event on the OuterGrid due to the MouseLeftButtonEvent not being handled at the InnerGrid level.
Is there a way I can notify the EventTrigger that it is handled and it should not bubble up to the OuterGrid?
At the moment, all I can think to do is have a wrapper FrameworkElement around the InnerGrid that uses an event on the XAML code-behind to set the event to handled. Does anyone have any other ideas?
---- Edit ----
In the end, I have included MVVM Light in my application and replaced InvokeCommandAction with RelayCommand. This is now working as I intended. I'll mark Bryant's answer as the winner for giving me the suggestion.
We have extended EventTrigger by adding dependency property called IsInner and then we always set a static flag in the inner EventTrigger. The outer EventTrigger unsets the flag and returns if the flag was set. That is extremely easy to write and works well.
Your best bet would be to pass the event args to the Command and then mark the event handled using the event args. You can do this by following this example here.

Resources