TextBox.TextChanged & ICommandSource - wpf

I am following the M-V-VM pattern for my WPF UI. I would like to hook up a command to the TextChanged event of a TextBox to a command that is in my ViewModel class. The only way I can conceive of completing this task is to inherit from the TextBox control, and implement ICommandSource. I can then instruct the command to be fired from the TextChanged event. This seems to be too much work for something which appears to be so simple.
Is there an easier way (than subclassing the TextBox and implementing ICommandSource) to hook up the TextChanged event to my ViewModel class?

First off, you've surely considered two-way data binding to your viewmodel, with an UpdateSourceTrigger of PropertyChanged? That way the property setter of the property you bind to will be called every time the text is changed?
If that's not enough, then I would tackle this problem using Attached Behaviours. On Julian Dominguez’s Blog you'll find an article about how to do something very similar in Silverlight, which should be easily adaptable to WPF.
Basically, in a static class (called, say TextBoxBehaviours) you define an Attached Property called (perhaps) TextChangedCommand of type ICommand. Hook up an OnPropertyChanged handler for that property, and within the handler, check that the property is being set on a TextBox; if it is, add a handler to the TextChanged event on the textbox that will call the command specified in the property.
Then, assuming your viewmodel has been assigned to the DataContext of your View, you would use it like:
<TextBox
x:Name="MyTextBox"
TextBoxBehaviours.TextChangedCommand="{Binding ViewModelTextChangedCommand}" />

Using the event binding and command method might not be the right thing to use.
What exactly will this command do?
You might want to consider using a Databinding to a string field in your VM. This way you can make a call to a command or function from there rather than having the UI care at all.
<TextBox Text="{Binding WorldName}"/>
....
public string WorldName
{
get
{
return WorldData.Name;
}
set
{
WorldData.Name = value;
OnPropertyChanged("WorldName");
// CallYourCustomFunctionHere();
}
}

Can you not just handle the TextChanged event and execute the command from there?
private void _textBox_TextChanged(object sender, EventArgs e)
{
MyCommand.Execute(null);
}
The alternative, as you say, is to create a TextBox that acts as a command source, but that does seem like overkill unless it's something you're planning on sharing and leveraging in many places.

Related

wpf: TextChanged event fired on setting DataContext

I've got a simple View with a single textbox that gets databound to a simple ViewModel with a single string property.
I need to catch the TextChanged event of that textbox so that I can do a little validation magic.
The problem that I am running into is that the TextChanged event fires for that textbox when the DataContext is set for the View.
Is there a standard mechanism that I can use to determine if the event is firing because of the DataContext being set versus when the user is making changes?
Thanks!
As far as I know there is no such mechanism. What you should do instead is to do your validation magic using standard means of WPF. Please see the following link: http://msdn.microsoft.com/en-us/library/ms752347.aspx#data_validation.
Anyway, as long as you use MVVM you can always detect that text has changed in the setter of the bound property in your view model.

S/L 4 & IDataErrorInfo - How to force re-validation of a control (when a related control is touched)

I have two controls bound to properties MinCartValue and MaxCartValue. MinCartValue must be less than MaxCartValue. To achieve this validation I have implemented the the IDataErrorInfo interface, and run the above check in the this[columnName] method if either MinCartValue or MaxCartValue are touched. ValidatesOnDataErrors=True is set in the binding of both controls.
The validation works correctly, highlighting each control when a change to its property value violates the rule. The problem is that once a control is flagged as invalid, if the user corrects the problem by altering the other control's value, the first control remains flagged as invalid. This is understandable because the IDataErrorInfo method was not doing validation on the first control's property.
So what I need is a way to force property #1 to be re-validated (or a way to clear the invalid state) when property #2 is validated, and vice versa. I have tried calling RaisePropertyChanged within my this[columnName] method but it does nothing. Also tried setting the property to its own value to try to trick it to validate itself, but again nothing happens.
Thanks
I would recommend looking at the INotifyDataErrorInfo interface (introduced in Silverlight 4). It's able to async-notify if properties become invalid, so I think the framework is better about respecting this across many properties instead of expecting that the property currently being changed is the only one whose validity may be changing.
I had two DateTime properties (DateFrom and DateTo) that needed to be validated against each other. In the setters for these properties I just raised a PropertyChanged event for both DateTo and DateFrom. Worked like a charm.
I'm not sure if I'm understanding your problem exactly, but perhaps this may help. Providing some example XAML and the binding property code would help.
It sounds like an issue of your code depending on the default UpdateSourceTrigger, which in the case of TextBox controls is their focus/unfocus. You can set in the XAML the UpdateSourceTrigger attribute by adding UpdateSourceTrigger=Explicit to your binding where your validation occurs. Then in each TextBox (MinCartValue, MaxCartValue), add an event handler to the TextChanged event.
In the code-behind in the event handler, you can do something like this:
private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
TheTextBox.GetBindingExpression(TextBox.TextProperty).UpdateSource();
}
TheTextBox in this case would be one of your cart controls. The UpdateSource() method is a way to manually update the binding value, which should trigger your validation. This method provides away to tie into a trigger to update values and raising properties have changed outside of the default scope (using text changed intead of focus and unfocus on TextBox in this instance).
Here's how I solved it. Let's say Property1 and Property2 are codependent. I'm not familiar with MVVM (yet), but you're probably extending your entity class to implement IDataErrorInfo. In this case you can also extend On[Property]Changed method and report change in codependent property:
partial class YourEntity : IDataErrorInfo
{
public string this[string columnName]
{
//Your validation logic
}
public string Error
{
//WPF doesn't use it anyway
get { return string.Empty; }
}
partial void OnProperty1Changed()
{
OnPropertyChanging("Property2");
OnPropertyChanged("Property2");
}
partial void OnProperty2Changed()
{
OnPropertyChanging("Property1");
OnPropertyChanged("Property1");
}
}
In this case the update in either one of this properties makes both bound controls re-evaluate themselves.
EDIT2: It appears that you should use OnPropertyChang* instead of ReportPropertyChang*. ReportPropertyChanged will notify the entity framework that there are pending changes in the model, but in fact all you're trying to do is inform the view. You don't want to update the database with the property that didn't really change. ReportPropertyChang* will also fail on computed fields that have no mappings in the database.
EDIT1: Found out that it's essential to call ReportPropertyChanging before ReportPropertyChanged.

Binding SelectionChanged to ViewModel using Caliburn.Micro

We've using Caliburn.Micro on a new Silverlight project and everythings working great. The inbuilt conventions bind buttons click events to the viewModel, but I'm not sure what the best way to handle the selectionChanged event on datagrids and comboboxes is.
At the moment, I'm binding to the selected item and calling custom logic, but I feel like this is a bit of a code smell and that I should seperate the setting of the property and the selectedChange event. But if I seperate these, how do I bind the selection changed event to my viewModel, by commands? or an EventTrigger? Or is the code below acceptable? Its a small change but I do this logic everywhere.
private Foo _selectedFoo;
public Foo SelectedFoo
{
get
{
return _Foo;
}
set
{
if (_Foo != null && _Foo.Equals(value)) return;
_Foo = value;
NotifyOfPropertyChange("SelectedFoo");
NotifyOfPropertyChange("CanRemove");
LoadRelatedBars();
}
}
I use this technique regularly and I feel very comfortable with it.
I find perfectly fine that the VM reacts to its own state change, without the need for the external actor (which incidentally is the View, but could be another component, too) to set the new state, THEN signal the VM that the state is changed.
If you really want to, however, you can use the Message.Attach attached property to hook an event in the View to an action in the VM:
cal:Message.Attach="[Event SelectionChanged] = [OnSelectionChangedAction]"
(see also https://caliburnmicro.com/documentation/actions)
Here is a sample for MVVM and Caliburn.Micro using. Some actions like SelectionChanged should get an explicit a event arguments, so you should set it in caliburn event action part. Freqently first argument is passing $this (The actual ui element to which the action is attached.) and you gets in handler a datacontext for the row but to get to the Grid you should pass $source, as the first argument ($source - is the actual FrameworkElement that triggered the ActionMessage to be sent). According to the manual Caliburn manual.
XAML
cal:Message.Attach="[Event SelectionChanged]=[Action DataGrid_JobTypesSelectionChanged($source,$eventArgs)];"
Code:
public void DataGrid_JobTypesSelectionChanged(object sender, SelectionChangedEventArgs e)
{
var grid = sender as DataGrid;
JobTypesSelectedCollection = grid.SelectedItems.Cast<JobComplexModel>().ToList();
}

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?

WPF - CanExecute doesn't fire when raising Commands from a UserControl

I've got a button strip usercontrol that I want to have on most of my forms.
I've added the commands as follows ...
public ICommand Create
{
get
{
return buttonCreate.Command;
}
set
{
buttonCreate.Command = value;
}
}
I've set these as dependency properties so I can bind to them ...
public static readonly DependencyProperty CreateCommandProperty =
DependencyProperty.Register(
"Create",
typeof(ICommand),
typeof(StandardButtonStrip),
new PropertyMetadata((ICommand)null));
I'm then binding my usercontrol to a command ...
<commoncontrols:StandardButtonStrip HorizontalAlignment="Stretch" Create="{Binding CreateCommand}" />
I'm setting up the command as follows ...
_viewModel.CreateCommand = new DelegateCommand<object>(OnCreateCommand, CanCreate);
but despite the fact that i'm always returning true on my CanCreate method the button is disabled ... if I put a break point on return true it never fires!
public bool CanCreate(object parm)
{
return true;
}
I've tried this to see if it will refresh the binding, but no joy!
_viewModel.CreateCommand.RaiseCanExecuteChanged();
I think the problem is down to the user control and how I'm passing the Command up as a property, but not sure ...
The way this looks, you have a dependency property on a view model. If you are really using MVVM, that is definetly not the way to go about it (not because of religious adherence to a pattern, but because it's not the optimal way).
First of all, is your view model a DependencyObject?
If it is, you should downgrade it to a class which implements INotifyPropertyChanged. Why? Because the Button's Command property is a DependencyProperty itself (inherited from ButtonBase) and supports databinding already.
If it isn't, then a dependency property on it will not work, which is fine, because you shouldn't have dependency properties on your view model in the first place.
What you should do, is have the view model as the DataContext for your control (I'm guessing you already have that set up). Then change your view model's CreateCommand to a plain ICommand, and bind the createButton's Command property like this (in your default StandardButtonStrip style)
<Button Name="createButton" HorizontalAlignment="Stretch" Command="{Binding CreateCommand}" />
This way, it will still be reusable, you just need to ensure that any view model you associate with your user control has a property CreateCommand of type ICommand (and that view model will be inherited down to the button control by default - one of the nicest things the wpf guys thought up).
So to recap, you should do it the other way around, more or less.
Hope this was helpful, cheers.
One caveat to the accepted answer -
Using a delegate command I could only get this to work if I created a new
Command<T> : DelegateCommand<T> and hooked up the Command Manager.
event EventHandler ICommand.CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
Have you overridden any of the user control's functionality?
One common problem is overriding a method without calling the base's implementation. For example, if you've overridden OnContentChanged() without calling base.OnContentChanged(), you may have accidentally supressed the firing of the ContentChanged event.

Resources