Silverlight MVVM: where did my (object sender, RoutedEventArgs e) go? - silverlight

I am using commanding in my viewmodel to handle events. like for example I am handling a button click event like this:
XAML
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<i:InvokeCommandAction Command="{Binding mvvmButtonclick}" />
</i:EventTrigger>
</i:Interaction.Triggers>
Viewmodel Code
public ICommand mvvmButtonclick
{
get;
private set;
}
Viewmodel Constructor code to wireup the command
this.mvvmButtonclick = new ActionCommand(this.ButtonClickedEvent);
Actual method in the viewmodel that gets called on button click
private void ButtonClickedEvent()
{
MessageBox.Show("worked!!!");
}
This works. So my questions are:
Is this the correct way?
Is there a way I can propogate the (object sender, RoutedEventArgs e) parameters into my viewmodel and should I care if its not there?
Suppose if this were a listbox selection changed event and not a button click. How do I get the value of the selected item without the object sender, SelectionChangedEventArgs e parameters?

I think you may be missing the point of the separation between view and view-model that the interaction triggers are designed to provide.
The purpose of the interaction triggers is to allow the designer (typically using Blend) to invoke a command on the view model. Which UI element and which event on the UI element might invoke such a command is the designers choice.
If the ViewModel though did require that a specific derivative of the EventArgs be provided during such a call to a command then that would tie the designers hands a little. It would create the sort of coupling between the view and view-model that interaction triggers aspires to eliminate.
As to your final question, the way to determine the currently selected item in a list box and be notified when it changes would be to create a property on the view model that is the bound to the SelectedItem of the ListBox. There is no need to employee interaction triggers or commands for this sort of thing.

There are some frameworks (such as Catel), that allow the forwarding of the EventArgs. For example, see this implementation:
http://catel.codeplex.com/SourceControl/changeset/view/508b404f2c57#src%2fCatel.Windows35%2fMVVM%2fCommands%2fCommand.cs
The class is compatible with both Silverlight and WPF.
If you don't want to use the EventArgs, you will need to create a SelectedObject property on the ViewModel and bind it to the SelectedItem of the listbox.
Catel includes 2 example applications (both in WPF and Silverlight) that use MVVM and the EventToCommand class to edit a selected item in a listbox. I think that is what you are looking for!

Related

WPF MVVM Where do you put UI Functions that wouldn't appear on your ViewModel

My understanding is that when you take your View and say:
myView.DataContext = myViewModel;
You are kind of assigning the class that it should refer to, almost like the code-behind in a most apps. I've always loved the design but where is the best place to put display type logic that really doesn't belong in your view model? For example say you're modifying a context menu for an item depending on the item's status. In the past I've handled different bits of display functionality with converters. I was going to use the Views native code behind but then I realized I don't think I have access to that do I?
Typically you would have a model object for each item in your list. Then wrap each model in a view model. The view model would then expose properties for the attributes you described (colors, fonts, etc.) and fire property change notifications. Hope that helps.
My assumption that setting the DataContext for a View was the same as pointing it to a different code behind file was incorrect. The DataContext is used for binding purposes. You can still reference methods in the normal code behind like so:
<CheckBox Margin="5,0,30,0"
x:Name="OSHPD" IsChecked="{Binding OSHPD}"
Validation.ErrorTemplate="{x:Null}" Checked="OSHPD_Checked" Unchecked="OSHPD_Unchecked">OSHPD Approval</CheckBox>
private void OSHPD_Checked(object sender, RoutedEventArgs e)
{
FM.IsEnabled = false;
}
private void OSHPD_Unchecked(object sender, RoutedEventArgs e)
{
FM.IsEnabled = true;
}
Databinding IsChecked="{Binding OSHPD}" is hitting the ViewModel while the events Checked="OSHPD_Checked" Unchecked="OSHPD_Unchecked" reference the Views code behind.
Most things that go in a View's code behind could also go in a ValueConverter, Behavior or AttachedProperty. Each of these will be able to access Control level properties. Generally you are able to supply these with values like the colours/brushes/shapes and other view specific data, to keep the valueConverter/behaviour/AttachedProperty generic if you did find you needed to reuse it.

WPF Calendar: Binding to MVVM commands?

I am wiring up a WPF calendar to an MVVM view model. I'm not sure how to bind date selections and month changes to MVVM ICommand objects. For example to process a selected date change, what object would I bind in XAML to the appropriate command property in my view model?
As nearly as I can tell, I am stuck with event handling in code-behind. For example, it looks like the only way to detect a date selection change is to write a SelectedDatesChanged event handler. I can invoke the command property in my view model from the event handler, like this:
private void Calendar_SelectedDatesChanged(object sender, SelectionChangedEventArgs e)
{
var viewModel = (CalendarViewModel) DataContext;
viewModel.GetDateNotes.Execute();
}
But I sense a code smell to that approach, unless there is no better approach available. Can anyone tell me how to bind a WPF Calendar to MVVM commands directly from XAML? Is there a better approach than the one I am taking? Thanks for your help.
Wouldn't you have a DateTime property in your VM that is bound to the calendar and that raises PropertyChanged? If so, can't you watch for property changed internally or write code in your setter so that you know when the view has changed its value?

how to bind the click event of a button and the selecteditemchanged of a listbox to a viewmodel in mvvm in Silverlight

i'm just starting with the mvvm model in Silverlight.
In step 1 i got a listbox bound to my viewmodel, but now i want to propagate a click in a button and a selecteditemchanged of the listbox back to the viewmodel.
I guess i have to bind the click event of the button and the selecteditemchanged of the listbox to 2 methods in my viewmodel somehow?
For the selecteditemchanged of the listbox i think there must also be a 'return call' possible when the viewmodel tries to set the selecteditem to another value?
i come from a asp.net (mvc) background, but can't figure out how to do it in silverlight.
Roboblob provides excellent step-by-step solution for Silverlight 4. It strictly follows MVVM paradigm.
I would not bind or tie the VM in any way directly to the events of controls within the View. Instead, have a separate event that is raised by the View in response to the button click.
[disclaimer: this code is all done straight from my head, not copy & pasted from VS - treat it as an example!!]
So in pseudo code, the View will look like this:
private void MyView_Loaded(...)
{
MyButton.Click += new EventHandler(MyButton_Click);
}
private void MyButton_Click(...)
{
//Raise my event:
OnUserPressedGo();
}
private void OnUserPressedGo()
{
if (UserPressedTheGoButton != null)
this.UserPressedTheGoButton(this, EventArgs.Empty);
}
public EventHandler UserPressedTheGoButton;
and the VM would have a line like this:
MyView.UserPressedTheGoButton += new EventHandler(myHandler);
this may seem a little long-winded, why not do it a bit more directly? The main reason for this is you do not want to tie your VM too tightly (if at all) to the contents of the View, otherwise it becomes difficult to change the View. Having one UI agnostic event like this means the button can change at any time without affecting the VM - you could change it from a button to a hyperlink or that kool kat designer you hire may change it to something totally weird and funky, it doesn't matter.
Now, let's talk about the SelectedItemChanged event of the listbox. Chances are you want to intercept an event for this so that you can modify the data bound to another control in the View. If this is a correct assumption, then read on - if i'm wrong then stop reading and reuse the example from above :)
The odds are that you may be able to get away with not needing a handler for that event. If you bind the SelectedItem of the listbox to a property in the VM:
<ListBox ItemSource={Binding SomeList} SelectedItem={Binding MyListSelectedItem} />
and then in the MyListSelectedItem property of the VM:
public object MyListSelectedItem
{
get { return _myListSelectedItem; }
set
{
bool changed = _myListSelectedItem != value;
if (changed)
{
_myListSelectedItem = value;
OnPropertyChanged("MyListSelectedItem");
}
}
}
private void OnPropertyChanged(string propertyName)
{
if (this.NotifyPropertyChanged != null)
this.NotifyPropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
To get that NotifyPropertyChanged event, just implement the INotifyPropertyChanged interface on your VM (which you should have done already). That is the basic stuff out of the way... what you then follow this up with is a NotifyPropertyChanged event handler on the VM itself:
private void ViewModel_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
switch (e.PropertyName)
{
case "MyListSelectedItem":
//at this point i know the value of MyListSelectedItem has changed, so
//i can now retrieve its value and use it to modify a secondary
//piece of data:
MySecondaryList = AllAvailableItemsForSecondaryList.Select(p => p.Id == MyListSelectedItem.Id);
break;
}
}
All you need now is for MySecondaryList to also notify that its value has changed:
public List<someObject> MySecondaryList
{
get { return _mySecondaryList; }
set
{
bool changed = .......;
if (changed)
{
... etc ...
OnNotifyPropertyChanged("MySecondaryList");
}
}
}
and anything bound to it will automatically be updated. Once again, it may seem that this is the long way to do things, but it means you have avoided having any handlers for UI events from the View, you have kept the abstraction between the View and the ViewModel.
I hope this has made some sense to you. With my code, i try to have the ViewModel knowing absolutely zero about the View, and the View only knowing the bare minimum about the ViewModel (the View recieves the ViewModel as an interface, so it can only know what the interface has specified).
Regarding binding the button click event I can recommend Laurent Bugnion's MVVM Light Toolkit (http://www.galasoft.ch/mvvm/getstarted/) as a way of dealing with this, I'll provide a little example, but Laurent's documentation is most likely a better way of understanding his framework.
Reference a couple of assemblies in your xaml page
xmlns:command="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Extras"
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
add a blend behaviour to the button
<Button Content="Press Me">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<command:EventToCommand Command="{Binding ViewModelEventName}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
and create the event within your viewmodel which will be called when the button is clicked
public RelayCommand ViewModelEventName { get; protected set; }
...
public PageViewModel()
{
ViewModelEventName = new RelayCommand(
() => DoWork()
);
}
This supports passing parameters, checking whether execution is allowed etc also.
Although I haven't used it myself, I think the Prism framework also allows you to do something similar.

Key press inside of textbox MVVM

I am just getting started with MVVM and im having problems figuring out how I can bind a key press inside a textbox to an ICommand inside the view model. I know I can do it in the code-behind but im trying to avoid that as much as possible.
Update: The solutions so far are all well and good if you have the blend sdk or your not having problems with the interaction dll which is what i'm having. Is there any other more generic solutions than having to use the blend sdk?
First of all, if you want to bind a RoutedUICommand it is easy - just add to the UIElement.InputBindings collection:
<TextBox ...>
<TextBox.InputBindings>
<KeyBinding
Key="Q"
Modifiers="Control"
Command="my:ModelAirplaneViewModel.AddGlueCommand" />
Your trouble starts when you try to set Command="{Binding AddGlueCommand}" to get the ICommand from the ViewModel. Since Command is not a DependencyProperty you can't set a Binding on it.
Your next attempt would probably be to create an attached property BindableCommand that has a PropertyChangedCallback that updates Command. This does allow you to access the binding but there is no way to use FindAncestor to find your ViewModel since the InputBindings collection doesn't set an InheritanceContext.
Obviously you could create an attached property that you could apply to the TextBox that would run through all the InputBindings calling BindingOperations.GetBinding on each to find Command bindings and updating those Bindings with an explicit source, allowing you to do this:
<TextBox my:BindingHelper.SetDataContextOnInputBindings="true">
<TextBox.InputBindings>
<KeyBinding
Key="Q"
Modifiers="Control"
my:BindingHelper.BindableCommand="{Binding ModelGlueCommand}" />
This attached property would be easy to implement: On PropertyChangedCallback it would schedule a "refresh" at DispatcherPriority.Input and set up an event so the "refresh" is rescheduled on every DataContext change. Then in the "refresh" code just, just set DataContext on each InputBinding:
...
public static readonly SetDataContextOnInputBindingsProperty = DependencyProperty.Register(... , new UIPropetyMetadata
{
PropertyChangedCallback = (obj, e) =>
{
var element = obj as FrameworkElement;
ScheduleUpdate(element);
element.DataContextChanged += (obj2, e2) =>
{
ScheduleUpdate(element);
};
}
});
private void ScheduleUpdate(FrameworkElement element)
{
Dispatcher.BeginInvoke(DispatcherPriority.Input, new Action(() =>
{
UpdateDataContexts(element);
})
}
private void UpdateDataContexts(FrameworkElement target)
{
var context = target.DataContext;
foreach(var inputBinding in target.InputBindings)
inputBinding.SetValue(FrameworkElement.DataContextProperty, context);
}
An alternative to the two attached properties would be to create a CommandBinding subclass that receives a routed command and activates a bound command:
<Window.CommandBindings>
<my:CommandMapper Command="my:RoutedCommands.AddGlue" MapToCommand="{Binding AddGlue}" />
...
in this case, the InputBindings in each object would reference the routed command, not the binding. This command would then be routed up the the view and mapped.
The code for CommandMapper is relatively trivial:
public class CommandMapper : CommandBinding
{
... // declaration of DependencyProperty 'MapToCommand'
public CommandMapper() : base(Executed, CanExecute)
{
}
private void Executed(object sender, ExecutedRoutedEventArgs e)
{
if(MapToCommand!=null)
MapToCommand.Execute(e.Parameter);
}
private void CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute =
MapToCommand==null ? null :
MapToCommand.CanExecute(e.Parameter);
}
}
For my taste, I would prefer to go with the attached properties solution, since it is not much code and keeps me from having to declare each command twice (as a RoutedCommand and as a property of my ViewModel). The supporting code only occurs once and can be used in all of your projects.
On the other hand if you're only doing a one-off project and don't expect to reuse anything, maybe even the CommandMapper is overkill. As you mentioned, it is possible to simply handle the events manually.
The excellent WPF framework Caliburn solves this problem beautifully.
<TextBox cm:Message.Attach="[Gesture Key: Enter] = [Action Search]" />
The syntax [Action Search] binds to a method in the view model. No need for ICommands at all.
Perhaps the easiest transition from code-behind event handling to MVVM commands would be Triggers and Actions from Expression Blend Samples.
Here's a snippet of code that demonstrates how you can handle key down event inside of the text box with the command:
<TextBox>
<i:Interaction.Triggers>
<i:EventTrigger EventName="KeyDown">
<si:InvokeDataCommand Command="{Binding MyCommand}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</TextBox>
The best option would probably be to use an Attached Property to do this. If you have the Blend SDK, the Behavior<T> class makes this much simpler.
For example, it would be very easy to modify this TextBox Behavior to fire an ICommand on every key press instead of clicking a button on Enter.

Getting non-UI objects to respond to WPF command bindings

I have a ViewModel class which i want to respond to the built in Refresh command whic is fired from a button but i'm not sure how to declare the CommandTarget.
Briefly, my code is as below
The ViewModel constructor and CanExecute and Executed event handlers -
public ViewModel()
{
CommandBinding binding = new CommandBinding(NavigationCommands.Refresh, CommandHandler);
binding.CanExecute += new CanExecuteRoutedEventHandler(binding_CanExecute);
binding.Executed += new ExecutedRoutedEventHandler(binding_Executed);
CommandManager.RegisterClassCommandBinding(typeof(ViewModel), binding);
}
void binding_Executed(object sender, ExecutedRoutedEventArgs e)
{
Debug.Print("Refreshing...");
}
void binding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = true;
}
The markup is -
<Button Command="Refresh">refresh</Button>
Now, I've tried setting the CommandTarget on this button to {Binding Source={StaticResource ViewModel}} but i get a runtime saying Cannot convert the value in attribute 'CommandTarget' to object of type 'System.Windows.IInputElement'.
I'm new to commands so it's entirely possible I'm all kinds of wrong here. Anyhelp would be appreciated.
RoutedCommands and MVVM do not mix. RoutedCommands are tied to the visual tree and to rely on WPF's CommandBindings collection. You should implement your own ICommand classes that work with the MVVM pattern. Take a look at Prism's implementations for starters.
In my own MVVM projects, I have a couple of command implementations:
DelegateCommand. Calls provided delegates to determine whether the command can execute, and to execute the command.
ActiveAwareCommand. Works in conjunction with an interface (IActiveAware) and sends command executions to the currently active item. Multiple active aware implementations register themselves with the command, and the command automatically routes CanExecute / Execute calls to the currently active item.

Resources