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

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.

Related

Is it the right way that command parameter references a view control in MVVM pattern?

I'm making a page using MVVM pattern.
By the way, I had a question during implementing command.
It is 'Is it the right to send command parameter to UI control'?
For example, I have a TextBox control. When LostFocus event is fired, a validation command binded with TextBox will be raised and I will send an UI control as command parameter to display a validation failure message.
After a command is executed, I will change content value of UI control if validate is failed.
These are my scenario.
But I know a viewmodel should not reference any of views and its controls directly.
Please let me know how.
If your validation is evaluated in the code behind of your view/control then you are fine to send or pass a control.
I have to question what sort of validation is being done at the UI layer - it can be general input logic (like numbers only or only certain letters, etc), but it shouldn't involve any business logic. Your code behind could call a method on the viewmodel to perform business logic based validation, but it should avoid passing a control.
If you are simply looking for a way to make a generic validation method for multiple controls, then you should consider another way such as:
creating a custom usercontrol that has the validation
using an attached behavior
A view model should not have any references or any dependencies upon any UI control such as a TextBox.
Instead of passing a reference to the TextBox as a command parameter to the view model command, you should either pass the value of the Text property of the TextBox as a string argument or - even better - you should simply bind the Text property of the TextBox to a string source property of the view model:
<TextBox Text="{Binding YourViewModelProperty}" />
The source property will be set when the TextBox loses focus and you can easily kick off your validation logic in the setter:
private string _s;
public string YourViewModelProperty
{
get { return _s; }
set { _s = value; Validate(); }
}
This is how the MVVM pattern is supposed to be implemented.

WPF binding to a function?

Let me start by saying I am very new to WPF so be gentle.
It seems like this should be easy but I am just missing something. I have implemented INotifyPropertyChanged on a few classes/properties and started binding them to elements in XAML but now I have a little more complex binding to make then updating text or changing a color. What I need is when the Alarm property of my object is set to true I need to change colors, start an animation, create and display other elements in the control. I thought I could just call a function in my control when the property is changed but since WPF hides how an element is "bound" to the model's property I am not sure how to wire that up. Is there a better way to perform this type of more complex response to a property change? If not are there any samples out there? I have not been able to find anything close to what I am looking for but I may not be searching with the correct terms.
What I need is when the Alarm property of my object is set to true I
need to change colors, start an animation, create and display other
elements in the control.
Change colors: Bind the Color/Foreground of the element you want to change the color of, to the boolean that sets the alarm, and add an IValueConverter in the binding that returns a Brush based on the boolean.
Start an animation: Use a (data)trigger on whichever element needs to be animated, in that trigger, use a Storyboard to define the animation you want.
create and display other elements in the control: that really depends on how well you did your MVVM, if the elements are a visualisation of an ObservableCollection through a ListBox/ListView/ItemsControl (which it should), wire up a Command to whatever sets the alarm on/off (the Button class has a Command property built in, other UIElements may require the use of System.Windows.Interactivity) and in the method that this Command will point to, add a new item to the ObservableCollection, the ItemsControl will automatically reflect the change by adding a new control.
Of course this is just raw information, and you're probably not familiar will all these things, that's when Google comes into play ;)
HTH,
Bab.
For complex behaviour in response to a property changed event, you should use the following approach: (I'm typing this freestyle so pardon any minor syntax errors)
class MyClass : INotifyPropertyChanged
{
//Presumably you've already done this part
private object _myProperty = null;
public object MyProperty
{
get { return _myProperty; }
set
{
_myProperty = value;
NotifyPropertyChanged("MyProperty");
}
}
public MyClass()
{
this.PropertyChanged += My_PropertyChanged;
}
private void My_PropertyChanged( object sender, PropertyChangedEventArgs e)
{
if( e.PropertyName == "MyProperty" )
{
//Do Something complicated
}
}
Your timer / alarm just needs to update the bound property when it elapses. The property should then raise the PropertyChanged event to notify the GUI to update.
You should take a look at DataTriggers that get fired when a property changes in the view model. The EnterActions and ExitActions will allow you to play a Storyboard when the value of the property changes. Here's an example of how it is used MSDN. You can use a content control and style the Template or ContentTemplate to add all of your elements and have it control the Visibility or Opacity of the other elements.
I don't think you are looking at this right. Your class has logic, does calculation, enforces constraints, and enforces relationships among properties. If you have an alarm hopefully there is some business logic to deal with this and should be done in the class (not the UI). A UI is not built to handle an alarm it is built to display status and actions of that alarm. You will make new control visible in an alarm situation and hide other. On the animation I think you might want to throw an event that you listen for to start the animation. The idea there is that when an alarm is thrown to can register additional handles - you want to separate the business logic from the UI (not pull the business logic into the UI).

Set UpdateSourceTrigger to Explicit in ShowDialog (WPF MVVM)

I saw this example - Binding.UpdateSourceTrigger Property
in the example the UpdateSourceTrigger set to Explicit and then in the view code he call to UpdateSource of the TextBox name.
But if i use the MVVM dp i dont want to have names to my controls and source properties are in the VM and not in the view so what is the right way to bind controls to VM properties and set the UpdateSourceTrigger to explicit?
I want to do this because in my case its ShowDialog window and I want that the source will update only if the user click "ok"
Thanks in advance!
If you are using MVVM truely then your OK button click must be handled by some Command. This command must be coming from your ViewModel. The Expliticly bound properties must be coming from your ViewModel again. So whats stopping you.
Do not use Explicit binding but use OneWay binding.
In you button, bind a command and bind a command parameter to the OneWay bound Dependency property.
In your Command's Execute handler (which must be some method from your ViewModel), change the ViewModel's property with the parameter coming.
Raise the NotifyPropertyChanged for that property from your ViewModel.
E.g.
Assume I need to update a TextBox's Text back into my model on OK button click.
So for that I have a EmployeeViewModel class that has EmployeeName property in it. The property is has a getter and a setter. The setter raises property changed notification. The view model also has another property of type ICommand named SaveNameCommand that return a command for me to execute.
EmployeeViewModel is the data context type of my view. Myview has a TextBox (named as x:Name="EmployeeNameTxBx") OneWay bound to the EmployeeName and a Button as OK. I bind Button.Command property to EmployeeViewModel.SaveNameCommand property and Button.CommandParameter is bound to EmployeeNameTxBx.Text property.
<StackPanel>
<TextBox x:Name="EmployeeNameTxBx"
Text="{Binding EmployeeName, Mode=OneWay}" />
<Button Content="OK"
Command="{Binding SaveNameCommand}"
CommandParameter="{Bidning Text, ElementName=EmployeeNameTxBx}" />
</StackPanel>
Inside my EmployeeViewModel I have OnSaveNameCommandExecute(object param) method to execute my SaveNameCommand.
In this perform this code...
var text = (string)param;
this.EmployeeName = text;
This way ONLY OK button click, updates the TextBox's text back into EmployeeName property of the model.
EDIT
Looking at your comments below, I see that you are trying to implement Validation on a UI. Now this changes things a little bit.
IDataErrorInfo and related validation works ONLY IF your input controls (such as TextBoxes) are TwoWay bound. Yes thats how it is intended. So now you may ask "Does this mean the whole concept of NOT ALLOWING invalid data to pass to model is futile in MVVM if we use IDataErrorInfo"?
Not actually!
See MVVM does not enforce a rule that ONLY valid data should come back. It accept invalid data and that is how IDataErrorInfo works and raises error notfications. The point is ViewModel is a mere softcopy of your View so it can be dirty. What it should make sure is that this dirtiness is not committed to your external interfaces such as services or data base.
Such invalid data flow should be restricted by the ViewModel by testing the invalid data. And that data will come if we have TwoWay binding enabled. So considering that you are implementing IDataErrorInfo then you need to have TwoWay bindings which is perfectly allowed in MVVM.
Approach 1:
What if I wan to explicitly validate certain items on the UI on button click?
For this use a delayed validation trick. In your ViewModel have a flag called isValidating. Set it false by default.
In your IDataErrorInfo.this property skip the validation by checking isValidating flag...
string IDataErrorInfo.this[string columnName]
{
get
{
if (!isValidating) return string.Empty;
string result = string.Empty;
bool value = false;
if (columnName == "EmployeeName")
{
if (string.IsNullOrEmpty(AccountType))
{
result = "EmployeeName cannot be empty!";
value = true;
}
}
return result;
}
}
Then in your OK command executed handler, check employee name and then raise property change notification events for the same property ...
private void OnSaveNameCommandExecute(object param)
{
isValidating = true;
this.NotifyPropertyChanged("EmployeeName");
isValidating = false;
}
This triggers the validation ONLY when you click OK. Remember that EmployeeName will HAVE to contain invalid data for the validation to work.
Approach 2:
What if I want to explicitly update bindings without TwoWay mode in MVVM?
Then you will have to use Attached Behavior. The behavior will attach to the OK button and will accept list of all items that need their bindings refreshed.
<Button Content="OK">
<local:SpecialBindingBehavior.DependentControls>
<MultiBinding Converter="{StaticResource ListMaker}">
<Binding ElementName="EmployeeNameTxBx" />
<Binding ElementName="EmployeeSalaryTxBx" />
....
<MultiBinding>
</local:SpecialBindingBehavior.DependentControls>
</Button>
The ListMaker is a IMultiValueConverter that simply converts values into a list...
Convert(object[] values, ...)
{
return values.ToList();
}
In your SpecialBindingBehavior have a DependentControls property changed handler...
private static void OnDependentControlsChanged(
DependencyObject depObj,
DependencyPropertyChangedEventArgs e)
{
var button = sender as Button;
if (button != null && e.NewValue is IList)
{
button.Click
+= new RoutedEventHandler(
(object s, RoutedEventArgs args) =>
{
foreach(var element in (IList)e.NewValue)
{
var bndExp
= ((TextBox)element).GetBindingExpression(
((TextBox)element).Textproperty);
bndExp.UpdateSource();
}
});
}
}
But I will still suggest you use my previous pure MVVM based **Approach 1.
This is an old question but still I want to provide an alternative approach for other users who stumble upon this question...
In my viewmodels, I do not expose the model properties directly in the get/set Property methods. I use internal variables for all the properties. Then I bind all the properties two-way. So I can do all the validation as "usual" because only the internal variables are changed. In the view model constructor, I have the model object as parameter and I set the internal variables to the values of my model. Now when I click on the "Save" Button (-> Save Command fires in my view model fires) and there are no errors, I set all the properties of my model to the values of the correspondng internal variable. If I click on the "Canel/Undo"-Button (-> Cancel-Command in my view model fires), I set the internal variables to the values of my untouched model (using the setters of the view model properties so that NotifyPropertyChanged is called and the view shows the changes=old values).
Yet another approach would be to implement Memento-Support in the model, so before you start editing you call a function in the model to save the current values, and if you cancel editing you call a function to restore those values...that way you would have the undo/cancel support everywhere an not just in one view model...
I've implemented both methods in different projects and both work fine, it depends on the requirements of the project...

DataContext, DataBinding and Element Binding in Silverlight

I'm having one hell of a time trying to get my databinding to work correctly. I have reason to believe that what I'm trying to accomplish can't be done, but we'll see what answers I get.
I've got a UserControl. This UserControl contains nothing more than a button. Now within the code behind, I've got a property name IsBookmarked. When IsBookmarked is set, code is run that animates the look of the button. The idea is that you click the button and it visually changes. We'll call this UserControl a Bookmark control.
Now I have another control, which we'll call the FormControl. My FormControl contains a child Bookmark control. I've tried to do databinding on my Bookmark control, but it's not working. Here's some code to help you out.
This is the XAML and Loaded event handler of my control. As you can see it contains a child element that is a custom control (bookmark). So once this control loads, it's DataContext is set to an new instance of an Employee object. Silverlight also sets the DataContext property of my child bookmark control to the same instance. I've verified this by debugging. If my parent has a valid DataContext set then why can't my child control (bookmark) property databind to it?
<UserControl ......>
<q:Bookmark x:Name="BookMarkControl1" IsBookmarked="{Binding IsSiteBookmarked}" />
</UserControl>
public void Control_Loaded(object sender, EventArgs e)
{
DataContext = new Employee { IsSiteBookmarked = True };
}
This is my custom control below. Obviously it contains more than this, but for readability I've trimmed it down to the property I'm trying to databind to.
//this is the bookmark control. I've included this control within another control, and I'm trying to databind to properties within my parents DataContext
public partial class Bookmark : UserControl
{
bool _IsBookmarked= false;
public bool IsBookmarked
{
get {return _IsBookmarked;}
set {
_IsBookmarked= value;
SwitchMode(value);
}
}
}
UPDATE
Got some javascript errors that I should mention. Firebug reports a AG_E_PARSER_BAD_PROPERTY_VALUE exception. It doesn't seem like my databinding is even working yet.
Make your IsBookmarked property on the Bookmark control a dependency property.
I presume Control_Loaded is a part of your FormControl, in which case I'm not sure you are using DataContext properly. Best double check that.
UPDATE: Yes, you are using the DataContext properly. AG_E_PARSER_BAD_PROPERTY_VALUE indicates you need to make the IsBookmarked property a dependency property, like so:
Public Property IsBookmarked() As Boolean
Get
Return Me.GetValue(IsBookmarkedProperty)
End Get
Set(ByVal value As Boolean)
Me.SetValue(IsBookmarkedProperty, value)
End Set
End Property
Public Shared ReadOnly IsBookmarkedProperty As DependencyProperty = DependencyProperty.Register("IsBookmarked", GetType(Boolean), GetType(Bookmark), New PropertyMetadata(New PropertyChangedCallback(AddressOf OnIsBookmarkedPropertyChanged)))
Private Shared Sub OnIsBookmarkedPropertyChanged(ByVal d As DependencyObject, ByVal e As DependencyPropertyChangedEventArgs)
Dim cntrl As Bookmark = TryCast(d, Bookmark)
cntrl.SetIsBookmarked(e.NewValue)
End Sub
If you only need to store the value for later use, then you don't need to do anything in the OnIsBookmarkedPropertyChanged procedure, But I put some code there as an example anyway.
Good Luck!
I don't recall the exact order in which databinding is evaluated (and I'm too lazy to go look it up), but as I recall, it initially happens BEFORE the form's Loaded event fires, and without making the IsBookmarked property a dependency property, or at least using INotifyPropertyChanged, it may have trouble establishing the datacontext appropriately. I'd recommend either implementing INotifyPropertyChanged or making IsBookmarked a dependency property. DataBinding is tough enough to get right in the best of circumstances (see my long, bad-tempered rant about it here), and you'll just be making it more difficult on yourself if you aren't setting up your properties in the way that it expects.
The control exposes a IsSiteBookmarked property(which I believe should be a DependencyProperty) but the control is binding to a IsBookmarked which is not shown. Is this intentional? Have you checked your Visual Studio output window for binding errors?
Addition 1:
Since you have fixed the typo in your question and added that there is an error being reported.
Start by clearing up the AG_E_PARSER_BAD_PROPERTY_VALUE problem. Is there a line number and start position in the error message? Start looking there. One strategy is to start taking out XAML until there is no longer an error. This will narrow down the offending code.
Running in debug, mode check for binding errors in the output window.
You might want to also post the Employee class code, especially the IsSiteBookmarked property.
Typically when doing databinding to an object you will want to leverage the INotifyPropertyChanged interface and implement that so that the control can properly invalidate it's property value. Unless you use INotifyPropertyChanged with Mode=TwoWay then any code that changes your DataContext's IsSiteBookmarked will have no effect.

TextBox.TextChanged & ICommandSource

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.

Resources